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/findinfiles/widgets.py
ResultsBrowser.append_result
def append_result(self, results, num_matches): """Real-time update of search results""" filename, lineno, colno, match_end, line = results if filename not in self.files: file_item = FileMatchItem(self, filename, self.sorting, self.text_color) file_item.setExpanded(True) self.files[filename] = file_item self.num_files += 1 search_text = self.search_text title = "'%s' - " % search_text nb_files = self.num_files if nb_files == 0: text = _('String not found') else: text_matches = _('matches in') text_files = _('file') if nb_files > 1: text_files += 's' text = "%d %s %d %s" % (num_matches, text_matches, nb_files, text_files) self.set_title(title + text) file_item = self.files[filename] line = self.truncate_result(line, colno, match_end) item = LineMatchItem(file_item, lineno, colno, line, self.text_color) self.data[id(item)] = (filename, lineno, colno)
python
def append_result(self, results, num_matches): """Real-time update of search results""" filename, lineno, colno, match_end, line = results if filename not in self.files: file_item = FileMatchItem(self, filename, self.sorting, self.text_color) file_item.setExpanded(True) self.files[filename] = file_item self.num_files += 1 search_text = self.search_text title = "'%s' - " % search_text nb_files = self.num_files if nb_files == 0: text = _('String not found') else: text_matches = _('matches in') text_files = _('file') if nb_files > 1: text_files += 's' text = "%d %s %d %s" % (num_matches, text_matches, nb_files, text_files) self.set_title(title + text) file_item = self.files[filename] line = self.truncate_result(line, colno, match_end) item = LineMatchItem(file_item, lineno, colno, line, self.text_color) self.data[id(item)] = (filename, lineno, colno)
[ "def", "append_result", "(", "self", ",", "results", ",", "num_matches", ")", ":", "filename", ",", "lineno", ",", "colno", ",", "match_end", ",", "line", "=", "results", "if", "filename", "not", "in", "self", ".", "files", ":", "file_item", "=", "FileMatchItem", "(", "self", ",", "filename", ",", "self", ".", "sorting", ",", "self", ".", "text_color", ")", "file_item", ".", "setExpanded", "(", "True", ")", "self", ".", "files", "[", "filename", "]", "=", "file_item", "self", ".", "num_files", "+=", "1", "search_text", "=", "self", ".", "search_text", "title", "=", "\"'%s' - \"", "%", "search_text", "nb_files", "=", "self", ".", "num_files", "if", "nb_files", "==", "0", ":", "text", "=", "_", "(", "'String not found'", ")", "else", ":", "text_matches", "=", "_", "(", "'matches in'", ")", "text_files", "=", "_", "(", "'file'", ")", "if", "nb_files", ">", "1", ":", "text_files", "+=", "'s'", "text", "=", "\"%d %s %d %s\"", "%", "(", "num_matches", ",", "text_matches", ",", "nb_files", ",", "text_files", ")", "self", ".", "set_title", "(", "title", "+", "text", ")", "file_item", "=", "self", ".", "files", "[", "filename", "]", "line", "=", "self", ".", "truncate_result", "(", "line", ",", "colno", ",", "match_end", ")", "item", "=", "LineMatchItem", "(", "file_item", ",", "lineno", ",", "colno", ",", "line", ",", "self", ".", "text_color", ")", "self", ".", "data", "[", "id", "(", "item", ")", "]", "=", "(", "filename", ",", "lineno", ",", "colno", ")" ]
Real-time update of search results
[ "Real", "-", "time", "update", "of", "search", "results" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L876-L904
train
spyder-ide/spyder
spyder/plugins/findinfiles/widgets.py
FileProgressBar.showEvent
def showEvent(self, event): """Override show event to start waiting spinner.""" QWidget.showEvent(self, event) self.spinner.start()
python
def showEvent(self, event): """Override show event to start waiting spinner.""" QWidget.showEvent(self, event) self.spinner.start()
[ "def", "showEvent", "(", "self", ",", "event", ")", ":", "QWidget", ".", "showEvent", "(", "self", ",", "event", ")", "self", ".", "spinner", ".", "start", "(", ")" ]
Override show event to start waiting spinner.
[ "Override", "show", "event", "to", "start", "waiting", "spinner", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L934-L937
train
spyder-ide/spyder
spyder/plugins/findinfiles/widgets.py
FileProgressBar.hideEvent
def hideEvent(self, event): """Override hide event to stop waiting spinner.""" QWidget.hideEvent(self, event) self.spinner.stop()
python
def hideEvent(self, event): """Override hide event to stop waiting spinner.""" QWidget.hideEvent(self, event) self.spinner.stop()
[ "def", "hideEvent", "(", "self", ",", "event", ")", ":", "QWidget", ".", "hideEvent", "(", "self", ",", "event", ")", "self", ".", "spinner", ".", "stop", "(", ")" ]
Override hide event to stop waiting spinner.
[ "Override", "hide", "event", "to", "stop", "waiting", "spinner", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L939-L942
train
spyder-ide/spyder
spyder/plugins/findinfiles/widgets.py
FindInFilesWidget.find
def find(self): """Call the find function""" options = self.find_options.get_options() if options is None: return self.stop_and_reset_thread(ignore_results=True) self.search_thread = SearchThread(self) self.search_thread.sig_finished.connect(self.search_complete) self.search_thread.sig_current_file.connect( lambda x: self.status_bar.set_label_path(x, folder=False) ) self.search_thread.sig_current_folder.connect( lambda x: self.status_bar.set_label_path(x, folder=True) ) self.search_thread.sig_file_match.connect( self.result_browser.append_result ) self.search_thread.sig_out_print.connect( lambda x: sys.stdout.write(str(x) + "\n") ) self.status_bar.reset() self.result_browser.clear_title( self.find_options.search_text.currentText()) self.search_thread.initialize(*options) self.search_thread.start() self.find_options.ok_button.setEnabled(False) self.find_options.stop_button.setEnabled(True) self.status_bar.show()
python
def find(self): """Call the find function""" options = self.find_options.get_options() if options is None: return self.stop_and_reset_thread(ignore_results=True) self.search_thread = SearchThread(self) self.search_thread.sig_finished.connect(self.search_complete) self.search_thread.sig_current_file.connect( lambda x: self.status_bar.set_label_path(x, folder=False) ) self.search_thread.sig_current_folder.connect( lambda x: self.status_bar.set_label_path(x, folder=True) ) self.search_thread.sig_file_match.connect( self.result_browser.append_result ) self.search_thread.sig_out_print.connect( lambda x: sys.stdout.write(str(x) + "\n") ) self.status_bar.reset() self.result_browser.clear_title( self.find_options.search_text.currentText()) self.search_thread.initialize(*options) self.search_thread.start() self.find_options.ok_button.setEnabled(False) self.find_options.stop_button.setEnabled(True) self.status_bar.show()
[ "def", "find", "(", "self", ")", ":", "options", "=", "self", ".", "find_options", ".", "get_options", "(", ")", "if", "options", "is", "None", ":", "return", "self", ".", "stop_and_reset_thread", "(", "ignore_results", "=", "True", ")", "self", ".", "search_thread", "=", "SearchThread", "(", "self", ")", "self", ".", "search_thread", ".", "sig_finished", ".", "connect", "(", "self", ".", "search_complete", ")", "self", ".", "search_thread", ".", "sig_current_file", ".", "connect", "(", "lambda", "x", ":", "self", ".", "status_bar", ".", "set_label_path", "(", "x", ",", "folder", "=", "False", ")", ")", "self", ".", "search_thread", ".", "sig_current_folder", ".", "connect", "(", "lambda", "x", ":", "self", ".", "status_bar", ".", "set_label_path", "(", "x", ",", "folder", "=", "True", ")", ")", "self", ".", "search_thread", ".", "sig_file_match", ".", "connect", "(", "self", ".", "result_browser", ".", "append_result", ")", "self", ".", "search_thread", ".", "sig_out_print", ".", "connect", "(", "lambda", "x", ":", "sys", ".", "stdout", ".", "write", "(", "str", "(", "x", ")", "+", "\"\\n\"", ")", ")", "self", ".", "status_bar", ".", "reset", "(", ")", "self", ".", "result_browser", ".", "clear_title", "(", "self", ".", "find_options", ".", "search_text", ".", "currentText", "(", ")", ")", "self", ".", "search_thread", ".", "initialize", "(", "*", "options", ")", "self", ".", "search_thread", ".", "start", "(", ")", "self", ".", "find_options", ".", "ok_button", ".", "setEnabled", "(", "False", ")", "self", ".", "find_options", ".", "stop_button", ".", "setEnabled", "(", "True", ")", "self", ".", "status_bar", ".", "show", "(", ")" ]
Call the find function
[ "Call", "the", "find", "function" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L1000-L1027
train
spyder-ide/spyder
spyder/plugins/findinfiles/widgets.py
FindInFilesWidget.stop_and_reset_thread
def stop_and_reset_thread(self, ignore_results=False): """Stop current search thread and clean-up""" if self.search_thread is not None: if self.search_thread.isRunning(): if ignore_results: self.search_thread.sig_finished.disconnect( self.search_complete) self.search_thread.stop() self.search_thread.wait() self.search_thread.setParent(None) self.search_thread = None
python
def stop_and_reset_thread(self, ignore_results=False): """Stop current search thread and clean-up""" if self.search_thread is not None: if self.search_thread.isRunning(): if ignore_results: self.search_thread.sig_finished.disconnect( self.search_complete) self.search_thread.stop() self.search_thread.wait() self.search_thread.setParent(None) self.search_thread = None
[ "def", "stop_and_reset_thread", "(", "self", ",", "ignore_results", "=", "False", ")", ":", "if", "self", ".", "search_thread", "is", "not", "None", ":", "if", "self", ".", "search_thread", ".", "isRunning", "(", ")", ":", "if", "ignore_results", ":", "self", ".", "search_thread", ".", "sig_finished", ".", "disconnect", "(", "self", ".", "search_complete", ")", "self", ".", "search_thread", ".", "stop", "(", ")", "self", ".", "search_thread", ".", "wait", "(", ")", "self", ".", "search_thread", ".", "setParent", "(", "None", ")", "self", ".", "search_thread", "=", "None" ]
Stop current search thread and clean-up
[ "Stop", "current", "search", "thread", "and", "clean", "-", "up" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L1029-L1039
train
spyder-ide/spyder
spyder/plugins/findinfiles/widgets.py
FindInFilesWidget.search_complete
def search_complete(self, completed): """Current search thread has finished""" self.result_browser.set_sorting(ON) self.find_options.ok_button.setEnabled(True) self.find_options.stop_button.setEnabled(False) self.status_bar.hide() self.result_browser.expandAll() if self.search_thread is None: return self.sig_finished.emit() found = self.search_thread.get_results() self.stop_and_reset_thread() if found is not None: results, pathlist, nb, error_flag = found self.result_browser.show()
python
def search_complete(self, completed): """Current search thread has finished""" self.result_browser.set_sorting(ON) self.find_options.ok_button.setEnabled(True) self.find_options.stop_button.setEnabled(False) self.status_bar.hide() self.result_browser.expandAll() if self.search_thread is None: return self.sig_finished.emit() found = self.search_thread.get_results() self.stop_and_reset_thread() if found is not None: results, pathlist, nb, error_flag = found self.result_browser.show()
[ "def", "search_complete", "(", "self", ",", "completed", ")", ":", "self", ".", "result_browser", ".", "set_sorting", "(", "ON", ")", "self", ".", "find_options", ".", "ok_button", ".", "setEnabled", "(", "True", ")", "self", ".", "find_options", ".", "stop_button", ".", "setEnabled", "(", "False", ")", "self", ".", "status_bar", ".", "hide", "(", ")", "self", ".", "result_browser", ".", "expandAll", "(", ")", "if", "self", ".", "search_thread", "is", "None", ":", "return", "self", ".", "sig_finished", ".", "emit", "(", ")", "found", "=", "self", ".", "search_thread", ".", "get_results", "(", ")", "self", ".", "stop_and_reset_thread", "(", ")", "if", "found", "is", "not", "None", ":", "results", ",", "pathlist", ",", "nb", ",", "error_flag", "=", "found", "self", ".", "result_browser", ".", "show", "(", ")" ]
Current search thread has finished
[ "Current", "search", "thread", "has", "finished" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L1045-L1059
train
spyder-ide/spyder
spyder/widgets/github/backend.py
GithubBackend._get_credentials_from_settings
def _get_credentials_from_settings(self): """Get the stored credentials if any.""" remember_me = CONF.get('main', 'report_error/remember_me') remember_token = CONF.get('main', 'report_error/remember_token') username = CONF.get('main', 'report_error/username', '') if not remember_me: username = '' return username, remember_me, remember_token
python
def _get_credentials_from_settings(self): """Get the stored credentials if any.""" remember_me = CONF.get('main', 'report_error/remember_me') remember_token = CONF.get('main', 'report_error/remember_token') username = CONF.get('main', 'report_error/username', '') if not remember_me: username = '' return username, remember_me, remember_token
[ "def", "_get_credentials_from_settings", "(", "self", ")", ":", "remember_me", "=", "CONF", ".", "get", "(", "'main'", ",", "'report_error/remember_me'", ")", "remember_token", "=", "CONF", ".", "get", "(", "'main'", ",", "'report_error/remember_token'", ")", "username", "=", "CONF", ".", "get", "(", "'main'", ",", "'report_error/username'", ",", "''", ")", "if", "not", "remember_me", ":", "username", "=", "''", "return", "username", ",", "remember_me", ",", "remember_token" ]
Get the stored credentials if any.
[ "Get", "the", "stored", "credentials", "if", "any", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/github/backend.py#L177-L185
train
spyder-ide/spyder
spyder/widgets/github/backend.py
GithubBackend._store_credentials
def _store_credentials(self, username, password, remember=False): """Store credentials for future use.""" if username and password and remember: CONF.set('main', 'report_error/username', username) try: keyring.set_password('github', username, password) except Exception: if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to store password'), _('It was not possible to securely ' 'save your password. You will be ' 'prompted for your Github ' 'credentials next time you want ' 'to report an issue.')) remember = False CONF.set('main', 'report_error/remember_me', remember)
python
def _store_credentials(self, username, password, remember=False): """Store credentials for future use.""" if username and password and remember: CONF.set('main', 'report_error/username', username) try: keyring.set_password('github', username, password) except Exception: if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to store password'), _('It was not possible to securely ' 'save your password. You will be ' 'prompted for your Github ' 'credentials next time you want ' 'to report an issue.')) remember = False CONF.set('main', 'report_error/remember_me', remember)
[ "def", "_store_credentials", "(", "self", ",", "username", ",", "password", ",", "remember", "=", "False", ")", ":", "if", "username", "and", "password", "and", "remember", ":", "CONF", ".", "set", "(", "'main'", ",", "'report_error/username'", ",", "username", ")", "try", ":", "keyring", ".", "set_password", "(", "'github'", ",", "username", ",", "password", ")", "except", "Exception", ":", "if", "self", ".", "_show_msgbox", ":", "QMessageBox", ".", "warning", "(", "self", ".", "parent_widget", ",", "_", "(", "'Failed to store password'", ")", ",", "_", "(", "'It was not possible to securely '", "'save your password. You will be '", "'prompted for your Github '", "'credentials next time you want '", "'to report an issue.'", ")", ")", "remember", "=", "False", "CONF", ".", "set", "(", "'main'", ",", "'report_error/remember_me'", ",", "remember", ")" ]
Store credentials for future use.
[ "Store", "credentials", "for", "future", "use", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/github/backend.py#L187-L203
train
spyder-ide/spyder
spyder/widgets/github/backend.py
GithubBackend._store_token
def _store_token(self, token, remember=False): """Store token for future use.""" if token and remember: try: keyring.set_password('github', 'token', token) except Exception: if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to store token'), _('It was not possible to securely ' 'save your token. You will be ' 'prompted for your Github token ' 'next time you want to report ' 'an issue.')) remember = False CONF.set('main', 'report_error/remember_token', remember)
python
def _store_token(self, token, remember=False): """Store token for future use.""" if token and remember: try: keyring.set_password('github', 'token', token) except Exception: if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to store token'), _('It was not possible to securely ' 'save your token. You will be ' 'prompted for your Github token ' 'next time you want to report ' 'an issue.')) remember = False CONF.set('main', 'report_error/remember_token', remember)
[ "def", "_store_token", "(", "self", ",", "token", ",", "remember", "=", "False", ")", ":", "if", "token", "and", "remember", ":", "try", ":", "keyring", ".", "set_password", "(", "'github'", ",", "'token'", ",", "token", ")", "except", "Exception", ":", "if", "self", ".", "_show_msgbox", ":", "QMessageBox", ".", "warning", "(", "self", ".", "parent_widget", ",", "_", "(", "'Failed to store token'", ")", ",", "_", "(", "'It was not possible to securely '", "'save your token. You will be '", "'prompted for your Github token '", "'next time you want to report '", "'an issue.'", ")", ")", "remember", "=", "False", "CONF", ".", "set", "(", "'main'", ",", "'report_error/remember_token'", ",", "remember", ")" ]
Store token for future use.
[ "Store", "token", "for", "future", "use", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/github/backend.py#L205-L220
train
spyder-ide/spyder
spyder/widgets/github/backend.py
GithubBackend.get_user_credentials
def get_user_credentials(self): """Get user credentials with the login dialog.""" password = None token = None (username, remember_me, remember_token) = self._get_credentials_from_settings() valid_py_os = not (PY2 and sys.platform.startswith('linux')) if username and remember_me and valid_py_os: # Get password from keyring try: password = keyring.get_password('github', username) except Exception: # No safe keyring backend if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to retrieve password'), _('It was not possible to retrieve ' 'your password. Please introduce ' 'it again.')) if remember_token and valid_py_os: # Get token from keyring try: token = keyring.get_password('github', 'token') except Exception: # No safe keyring backend if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to retrieve token'), _('It was not possible to retrieve ' 'your token. Please introduce it ' 'again.')) if not running_under_pytest(): credentials = DlgGitHubLogin.login(self.parent_widget, username, password, token, remember_me, remember_token) if (credentials['username'] and credentials['password'] and valid_py_os): self._store_credentials(credentials['username'], credentials['password'], credentials['remember']) CONF.set('main', 'report_error/remember_me', credentials['remember']) if credentials['token'] and valid_py_os: self._store_token(credentials['token'], credentials['remember_token']) CONF.set('main', 'report_error/remember_token', credentials['remember_token']) else: return dict(username=username, password=password, token='', remember=remember_me, remember_token=remember_token) return credentials
python
def get_user_credentials(self): """Get user credentials with the login dialog.""" password = None token = None (username, remember_me, remember_token) = self._get_credentials_from_settings() valid_py_os = not (PY2 and sys.platform.startswith('linux')) if username and remember_me and valid_py_os: # Get password from keyring try: password = keyring.get_password('github', username) except Exception: # No safe keyring backend if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to retrieve password'), _('It was not possible to retrieve ' 'your password. Please introduce ' 'it again.')) if remember_token and valid_py_os: # Get token from keyring try: token = keyring.get_password('github', 'token') except Exception: # No safe keyring backend if self._show_msgbox: QMessageBox.warning(self.parent_widget, _('Failed to retrieve token'), _('It was not possible to retrieve ' 'your token. Please introduce it ' 'again.')) if not running_under_pytest(): credentials = DlgGitHubLogin.login(self.parent_widget, username, password, token, remember_me, remember_token) if (credentials['username'] and credentials['password'] and valid_py_os): self._store_credentials(credentials['username'], credentials['password'], credentials['remember']) CONF.set('main', 'report_error/remember_me', credentials['remember']) if credentials['token'] and valid_py_os: self._store_token(credentials['token'], credentials['remember_token']) CONF.set('main', 'report_error/remember_token', credentials['remember_token']) else: return dict(username=username, password=password, token='', remember=remember_me, remember_token=remember_token) return credentials
[ "def", "get_user_credentials", "(", "self", ")", ":", "password", "=", "None", "token", "=", "None", "(", "username", ",", "remember_me", ",", "remember_token", ")", "=", "self", ".", "_get_credentials_from_settings", "(", ")", "valid_py_os", "=", "not", "(", "PY2", "and", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ")", "if", "username", "and", "remember_me", "and", "valid_py_os", ":", "# Get password from keyring", "try", ":", "password", "=", "keyring", ".", "get_password", "(", "'github'", ",", "username", ")", "except", "Exception", ":", "# No safe keyring backend", "if", "self", ".", "_show_msgbox", ":", "QMessageBox", ".", "warning", "(", "self", ".", "parent_widget", ",", "_", "(", "'Failed to retrieve password'", ")", ",", "_", "(", "'It was not possible to retrieve '", "'your password. Please introduce '", "'it again.'", ")", ")", "if", "remember_token", "and", "valid_py_os", ":", "# Get token from keyring", "try", ":", "token", "=", "keyring", ".", "get_password", "(", "'github'", ",", "'token'", ")", "except", "Exception", ":", "# No safe keyring backend", "if", "self", ".", "_show_msgbox", ":", "QMessageBox", ".", "warning", "(", "self", ".", "parent_widget", ",", "_", "(", "'Failed to retrieve token'", ")", ",", "_", "(", "'It was not possible to retrieve '", "'your token. Please introduce it '", "'again.'", ")", ")", "if", "not", "running_under_pytest", "(", ")", ":", "credentials", "=", "DlgGitHubLogin", ".", "login", "(", "self", ".", "parent_widget", ",", "username", ",", "password", ",", "token", ",", "remember_me", ",", "remember_token", ")", "if", "(", "credentials", "[", "'username'", "]", "and", "credentials", "[", "'password'", "]", "and", "valid_py_os", ")", ":", "self", ".", "_store_credentials", "(", "credentials", "[", "'username'", "]", ",", "credentials", "[", "'password'", "]", ",", "credentials", "[", "'remember'", "]", ")", "CONF", ".", "set", "(", "'main'", ",", "'report_error/remember_me'", ",", "credentials", "[", "'remember'", "]", ")", "if", "credentials", "[", "'token'", "]", "and", "valid_py_os", ":", "self", ".", "_store_token", "(", "credentials", "[", "'token'", "]", ",", "credentials", "[", "'remember_token'", "]", ")", "CONF", ".", "set", "(", "'main'", ",", "'report_error/remember_token'", ",", "credentials", "[", "'remember_token'", "]", ")", "else", ":", "return", "dict", "(", "username", "=", "username", ",", "password", "=", "password", ",", "token", "=", "''", ",", "remember", "=", "remember_me", ",", "remember_token", "=", "remember_token", ")", "return", "credentials" ]
Get user credentials with the login dialog.
[ "Get", "user", "credentials", "with", "the", "login", "dialog", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/github/backend.py#L223-L280
train
spyder-ide/spyder
spyder/widgets/calltip.py
ToolTipWidget.show_tip
def show_tip(self, point, tip): """ Attempts to show the specified tip at the current cursor location. """ # Don't attempt to show it if it's already visible and the text # to be displayed is the same as the one displayed before. if self.isVisible(): if self.tip == tip: return True else: self.hide() # Set the text and resize the widget accordingly. self.tip = tip self.setText(tip) self.resize(self.sizeHint()) self.move(point) self.show() return True
python
def show_tip(self, point, tip): """ Attempts to show the specified tip at the current cursor location. """ # Don't attempt to show it if it's already visible and the text # to be displayed is the same as the one displayed before. if self.isVisible(): if self.tip == tip: return True else: self.hide() # Set the text and resize the widget accordingly. self.tip = tip self.setText(tip) self.resize(self.sizeHint()) self.move(point) self.show() return True
[ "def", "show_tip", "(", "self", ",", "point", ",", "tip", ")", ":", "# Don't attempt to show it if it's already visible and the text", "# to be displayed is the same as the one displayed before.", "if", "self", ".", "isVisible", "(", ")", ":", "if", "self", ".", "tip", "==", "tip", ":", "return", "True", "else", ":", "self", ".", "hide", "(", ")", "# Set the text and resize the widget accordingly.", "self", ".", "tip", "=", "tip", "self", ".", "setText", "(", "tip", ")", "self", ".", "resize", "(", "self", ".", "sizeHint", "(", ")", ")", "self", ".", "move", "(", "point", ")", "self", ".", "show", "(", ")", "return", "True" ]
Attempts to show the specified tip at the current cursor location.
[ "Attempts", "to", "show", "the", "specified", "tip", "at", "the", "current", "cursor", "location", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L73-L91
train
spyder-ide/spyder
spyder/widgets/calltip.py
ToolTipWidget.leaveEvent
def leaveEvent(self, event): """Override Qt method to hide the tooltip on leave.""" super(ToolTipWidget, self).leaveEvent(event) self.hide()
python
def leaveEvent(self, event): """Override Qt method to hide the tooltip on leave.""" super(ToolTipWidget, self).leaveEvent(event) self.hide()
[ "def", "leaveEvent", "(", "self", ",", "event", ")", ":", "super", "(", "ToolTipWidget", ",", "self", ")", ".", "leaveEvent", "(", "event", ")", "self", ".", "hide", "(", ")" ]
Override Qt method to hide the tooltip on leave.
[ "Override", "Qt", "method", "to", "hide", "the", "tooltip", "on", "leave", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L105-L108
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.eventFilter
def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """ if obj == self._text_edit: etype = event.type() if etype == QEvent.KeyPress: key = event.key() cursor = self._text_edit.textCursor() prev_char = self._text_edit.get_character(cursor.position(), offset=-1) if key in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Down, Qt.Key_Up): self.hide() elif key == Qt.Key_Escape: self.hide() return True elif prev_char == ')': self.hide() elif etype == QEvent.FocusOut: self.hide() elif etype == QEvent.Enter: if (self._hide_timer.isActive() and self.app.topLevelAt(QCursor.pos()) == self): self._hide_timer.stop() elif etype == QEvent.Leave: self._leave_event_hide() return super(CallTipWidget, self).eventFilter(obj, event)
python
def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """ if obj == self._text_edit: etype = event.type() if etype == QEvent.KeyPress: key = event.key() cursor = self._text_edit.textCursor() prev_char = self._text_edit.get_character(cursor.position(), offset=-1) if key in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Down, Qt.Key_Up): self.hide() elif key == Qt.Key_Escape: self.hide() return True elif prev_char == ')': self.hide() elif etype == QEvent.FocusOut: self.hide() elif etype == QEvent.Enter: if (self._hide_timer.isActive() and self.app.topLevelAt(QCursor.pos()) == self): self._hide_timer.stop() elif etype == QEvent.Leave: self._leave_event_hide() return super(CallTipWidget, self).eventFilter(obj, event)
[ "def", "eventFilter", "(", "self", ",", "obj", ",", "event", ")", ":", "if", "obj", "==", "self", ".", "_text_edit", ":", "etype", "=", "event", ".", "type", "(", ")", "if", "etype", "==", "QEvent", ".", "KeyPress", ":", "key", "=", "event", ".", "key", "(", ")", "cursor", "=", "self", ".", "_text_edit", ".", "textCursor", "(", ")", "prev_char", "=", "self", ".", "_text_edit", ".", "get_character", "(", "cursor", ".", "position", "(", ")", ",", "offset", "=", "-", "1", ")", "if", "key", "in", "(", "Qt", ".", "Key_Enter", ",", "Qt", ".", "Key_Return", ",", "Qt", ".", "Key_Down", ",", "Qt", ".", "Key_Up", ")", ":", "self", ".", "hide", "(", ")", "elif", "key", "==", "Qt", ".", "Key_Escape", ":", "self", ".", "hide", "(", ")", "return", "True", "elif", "prev_char", "==", "')'", ":", "self", ".", "hide", "(", ")", "elif", "etype", "==", "QEvent", ".", "FocusOut", ":", "self", ".", "hide", "(", ")", "elif", "etype", "==", "QEvent", ".", "Enter", ":", "if", "(", "self", ".", "_hide_timer", ".", "isActive", "(", ")", "and", "self", ".", "app", ".", "topLevelAt", "(", "QCursor", ".", "pos", "(", ")", ")", "==", "self", ")", ":", "self", ".", "_hide_timer", ".", "stop", "(", ")", "elif", "etype", "==", "QEvent", ".", "Leave", ":", "self", ".", "_leave_event_hide", "(", ")", "return", "super", "(", "CallTipWidget", ",", "self", ")", ".", "eventFilter", "(", "obj", ",", "event", ")" ]
Reimplemented to hide on certain key presses and on text edit focus changes.
[ "Reimplemented", "to", "hide", "on", "certain", "key", "presses", "and", "on", "text", "edit", "focus", "changes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L144-L176
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.timerEvent
def timerEvent(self, event): """ Reimplemented to hide the widget when the hide timer fires. """ if event.timerId() == self._hide_timer.timerId(): self._hide_timer.stop() self.hide()
python
def timerEvent(self, event): """ Reimplemented to hide the widget when the hide timer fires. """ if event.timerId() == self._hide_timer.timerId(): self._hide_timer.stop() self.hide()
[ "def", "timerEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "timerId", "(", ")", "==", "self", ".", "_hide_timer", ".", "timerId", "(", ")", ":", "self", ".", "_hide_timer", ".", "stop", "(", ")", "self", ".", "hide", "(", ")" ]
Reimplemented to hide the widget when the hide timer fires.
[ "Reimplemented", "to", "hide", "the", "widget", "when", "the", "hide", "timer", "fires", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L178-L183
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.enterEvent
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """ super(CallTipWidget, self).enterEvent(event) if self.as_tooltip: self.hide() if (self._hide_timer.isActive() and self.app.topLevelAt(QCursor.pos()) == self): self._hide_timer.stop()
python
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """ super(CallTipWidget, self).enterEvent(event) if self.as_tooltip: self.hide() if (self._hide_timer.isActive() and self.app.topLevelAt(QCursor.pos()) == self): self._hide_timer.stop()
[ "def", "enterEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CallTipWidget", ",", "self", ")", ".", "enterEvent", "(", "event", ")", "if", "self", ".", "as_tooltip", ":", "self", ".", "hide", "(", ")", "if", "(", "self", ".", "_hide_timer", ".", "isActive", "(", ")", "and", "self", ".", "app", ".", "topLevelAt", "(", "QCursor", ".", "pos", "(", ")", ")", "==", "self", ")", ":", "self", ".", "_hide_timer", ".", "stop", "(", ")" ]
Reimplemented to cancel the hide timer.
[ "Reimplemented", "to", "cancel", "the", "hide", "timer", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L189-L198
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.hideEvent
def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """ super(CallTipWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect( self._cursor_position_changed) self._text_edit.removeEventFilter(self)
python
def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """ super(CallTipWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect( self._cursor_position_changed) self._text_edit.removeEventFilter(self)
[ "def", "hideEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CallTipWidget", ",", "self", ")", ".", "hideEvent", "(", "event", ")", "self", ".", "_text_edit", ".", "cursorPositionChanged", ".", "disconnect", "(", "self", ".", "_cursor_position_changed", ")", "self", ".", "_text_edit", ".", "removeEventFilter", "(", "self", ")" ]
Reimplemented to disconnect signal handlers and event filter.
[ "Reimplemented", "to", "disconnect", "signal", "handlers", "and", "event", "filter", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L200-L206
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.leaveEvent
def leaveEvent(self, event): """ Reimplemented to start the hide timer. """ super(CallTipWidget, self).leaveEvent(event) self._leave_event_hide()
python
def leaveEvent(self, event): """ Reimplemented to start the hide timer. """ super(CallTipWidget, self).leaveEvent(event) self._leave_event_hide()
[ "def", "leaveEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CallTipWidget", ",", "self", ")", ".", "leaveEvent", "(", "event", ")", "self", ".", "_leave_event_hide", "(", ")" ]
Reimplemented to start the hide timer.
[ "Reimplemented", "to", "start", "the", "hide", "timer", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L208-L212
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.showEvent
def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """ super(CallTipWidget, self).showEvent(event) self._text_edit.cursorPositionChanged.connect( self._cursor_position_changed) self._text_edit.installEventFilter(self)
python
def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """ super(CallTipWidget, self).showEvent(event) self._text_edit.cursorPositionChanged.connect( self._cursor_position_changed) self._text_edit.installEventFilter(self)
[ "def", "showEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CallTipWidget", ",", "self", ")", ".", "showEvent", "(", "event", ")", "self", ".", "_text_edit", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "_cursor_position_changed", ")", "self", ".", "_text_edit", ".", "installEventFilter", "(", "self", ")" ]
Reimplemented to connect signal handlers and event filter.
[ "Reimplemented", "to", "connect", "signal", "handlers", "and", "event", "filter", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L234-L240
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget.show_tip
def show_tip(self, point, tip, wrapped_tiplines): """ Attempts to show the specified tip at the current cursor location. """ # Don't attempt to show it if it's already visible and the text # to be displayed is the same as the one displayed before. if self.isVisible(): if self.tip == tip: return True else: self.hide() # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False if self.hide_timer_on: self._hide_timer.stop() # Logic to decide how much time to show the calltip depending # on the amount of text present if len(wrapped_tiplines) == 1: args = wrapped_tiplines[0].split('(')[1] nargs = len(args.split(',')) if nargs == 1: hide_time = 1400 elif nargs == 2: hide_time = 1600 else: hide_time = 1800 elif len(wrapped_tiplines) == 2: args1 = wrapped_tiplines[1].strip() nargs1 = len(args1.split(',')) if nargs1 == 1: hide_time = 2500 else: hide_time = 2800 else: hide_time = 3500 self._hide_timer.start(hide_time, self) # Set the text and resize the widget accordingly. self.tip = tip self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 3 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = self.app.desktop().screenGeometry(text_edit) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height() + screen_rect.y(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2*point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width() + screen_rect.x(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2*point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal)) adjusted_point = text_edit.mapToGlobal(pos()) if vertical == 'top': point.setY(adjusted_point.y() - tip_height - padding) if horizontal == 'Left': point.setX(adjusted_point.x() - tip_width - padding) self.move(point) self.show() return True
python
def show_tip(self, point, tip, wrapped_tiplines): """ Attempts to show the specified tip at the current cursor location. """ # Don't attempt to show it if it's already visible and the text # to be displayed is the same as the one displayed before. if self.isVisible(): if self.tip == tip: return True else: self.hide() # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False if self.hide_timer_on: self._hide_timer.stop() # Logic to decide how much time to show the calltip depending # on the amount of text present if len(wrapped_tiplines) == 1: args = wrapped_tiplines[0].split('(')[1] nargs = len(args.split(',')) if nargs == 1: hide_time = 1400 elif nargs == 2: hide_time = 1600 else: hide_time = 1800 elif len(wrapped_tiplines) == 2: args1 = wrapped_tiplines[1].strip() nargs1 = len(args1.split(',')) if nargs1 == 1: hide_time = 2500 else: hide_time = 2800 else: hide_time = 3500 self._hide_timer.start(hide_time, self) # Set the text and resize the widget accordingly. self.tip = tip self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 3 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = self.app.desktop().screenGeometry(text_edit) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height() + screen_rect.y(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2*point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width() + screen_rect.x(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2*point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal)) adjusted_point = text_edit.mapToGlobal(pos()) if vertical == 'top': point.setY(adjusted_point.y() - tip_height - padding) if horizontal == 'Left': point.setX(adjusted_point.x() - tip_width - padding) self.move(point) self.show() return True
[ "def", "show_tip", "(", "self", ",", "point", ",", "tip", ",", "wrapped_tiplines", ")", ":", "# Don't attempt to show it if it's already visible and the text", "# to be displayed is the same as the one displayed before.", "if", "self", ".", "isVisible", "(", ")", ":", "if", "self", ".", "tip", "==", "tip", ":", "return", "True", "else", ":", "self", ".", "hide", "(", ")", "# Attempt to find the cursor position at which to show the call tip.", "text_edit", "=", "self", ".", "_text_edit", "cursor", "=", "text_edit", ".", "textCursor", "(", ")", "search_pos", "=", "cursor", ".", "position", "(", ")", "-", "1", "self", ".", "_start_position", ",", "_", "=", "self", ".", "_find_parenthesis", "(", "search_pos", ",", "forward", "=", "False", ")", "if", "self", ".", "_start_position", "==", "-", "1", ":", "return", "False", "if", "self", ".", "hide_timer_on", ":", "self", ".", "_hide_timer", ".", "stop", "(", ")", "# Logic to decide how much time to show the calltip depending", "# on the amount of text present", "if", "len", "(", "wrapped_tiplines", ")", "==", "1", ":", "args", "=", "wrapped_tiplines", "[", "0", "]", ".", "split", "(", "'('", ")", "[", "1", "]", "nargs", "=", "len", "(", "args", ".", "split", "(", "','", ")", ")", "if", "nargs", "==", "1", ":", "hide_time", "=", "1400", "elif", "nargs", "==", "2", ":", "hide_time", "=", "1600", "else", ":", "hide_time", "=", "1800", "elif", "len", "(", "wrapped_tiplines", ")", "==", "2", ":", "args1", "=", "wrapped_tiplines", "[", "1", "]", ".", "strip", "(", ")", "nargs1", "=", "len", "(", "args1", ".", "split", "(", "','", ")", ")", "if", "nargs1", "==", "1", ":", "hide_time", "=", "2500", "else", ":", "hide_time", "=", "2800", "else", ":", "hide_time", "=", "3500", "self", ".", "_hide_timer", ".", "start", "(", "hide_time", ",", "self", ")", "# Set the text and resize the widget accordingly.", "self", ".", "tip", "=", "tip", "self", ".", "setText", "(", "tip", ")", "self", ".", "resize", "(", "self", ".", "sizeHint", "(", ")", ")", "# Locate and show the widget. Place the tip below the current line", "# unless it would be off the screen. In that case, decide the best", "# location based trying to minimize the area that goes off-screen.", "padding", "=", "3", "# Distance in pixels between cursor bounds and tip box.", "cursor_rect", "=", "text_edit", ".", "cursorRect", "(", "cursor", ")", "screen_rect", "=", "self", ".", "app", ".", "desktop", "(", ")", ".", "screenGeometry", "(", "text_edit", ")", "point", ".", "setY", "(", "point", ".", "y", "(", ")", "+", "padding", ")", "tip_height", "=", "self", ".", "size", "(", ")", ".", "height", "(", ")", "tip_width", "=", "self", ".", "size", "(", ")", ".", "width", "(", ")", "vertical", "=", "'bottom'", "horizontal", "=", "'Right'", "if", "point", ".", "y", "(", ")", "+", "tip_height", ">", "screen_rect", ".", "height", "(", ")", "+", "screen_rect", ".", "y", "(", ")", ":", "point_", "=", "text_edit", ".", "mapToGlobal", "(", "cursor_rect", ".", "topRight", "(", ")", ")", "# If tip is still off screen, check if point is in top or bottom", "# half of screen.", "if", "point_", ".", "y", "(", ")", "-", "tip_height", "<", "padding", ":", "# If point is in upper half of screen, show tip below it.", "# otherwise above it.", "if", "2", "*", "point", ".", "y", "(", ")", "<", "screen_rect", ".", "height", "(", ")", ":", "vertical", "=", "'bottom'", "else", ":", "vertical", "=", "'top'", "else", ":", "vertical", "=", "'top'", "if", "point", ".", "x", "(", ")", "+", "tip_width", ">", "screen_rect", ".", "width", "(", ")", "+", "screen_rect", ".", "x", "(", ")", ":", "point_", "=", "text_edit", ".", "mapToGlobal", "(", "cursor_rect", ".", "topRight", "(", ")", ")", "# If tip is still off-screen, check if point is in the right or", "# left half of the screen.", "if", "point_", ".", "x", "(", ")", "-", "tip_width", "<", "padding", ":", "if", "2", "*", "point", ".", "x", "(", ")", "<", "screen_rect", ".", "width", "(", ")", ":", "horizontal", "=", "'Right'", "else", ":", "horizontal", "=", "'Left'", "else", ":", "horizontal", "=", "'Left'", "pos", "=", "getattr", "(", "cursor_rect", ",", "'%s%s'", "%", "(", "vertical", ",", "horizontal", ")", ")", "adjusted_point", "=", "text_edit", ".", "mapToGlobal", "(", "pos", "(", ")", ")", "if", "vertical", "==", "'top'", ":", "point", ".", "setY", "(", "adjusted_point", ".", "y", "(", ")", "-", "tip_height", "-", "padding", ")", "if", "horizontal", "==", "'Left'", ":", "point", ".", "setX", "(", "adjusted_point", ".", "x", "(", ")", "-", "tip_width", "-", "padding", ")", "self", ".", "move", "(", "point", ")", "self", ".", "show", "(", ")", "return", "True" ]
Attempts to show the specified tip at the current cursor location.
[ "Attempts", "to", "show", "the", "specified", "tip", "at", "the", "current", "cursor", "location", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L252-L346
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget._leave_event_hide
def _leave_event_hide(self): """ Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip). """ if (self.hide_timer_on and not self._hide_timer.isActive() and # If Enter events always came after Leave events, we wouldn't need # this check. But on Mac OS, it sometimes happens the other way # around when the tooltip is created. self.app.topLevelAt(QCursor.pos()) != self): self._hide_timer.start(800, self)
python
def _leave_event_hide(self): """ Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip). """ if (self.hide_timer_on and not self._hide_timer.isActive() and # If Enter events always came after Leave events, we wouldn't need # this check. But on Mac OS, it sometimes happens the other way # around when the tooltip is created. self.app.topLevelAt(QCursor.pos()) != self): self._hide_timer.start(800, self)
[ "def", "_leave_event_hide", "(", "self", ")", ":", "if", "(", "self", ".", "hide_timer_on", "and", "not", "self", ".", "_hide_timer", ".", "isActive", "(", ")", "and", "# If Enter events always came after Leave events, we wouldn't need", "# this check. But on Mac OS, it sometimes happens the other way", "# around when the tooltip is created.", "self", ".", "app", ".", "topLevelAt", "(", "QCursor", ".", "pos", "(", ")", ")", "!=", "self", ")", ":", "self", ".", "_hide_timer", ".", "start", "(", "800", ",", "self", ")" ]
Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip).
[ "Hides", "the", "tooltip", "after", "some", "time", "has", "passed", "(", "assuming", "the", "cursor", "is", "not", "over", "the", "tooltip", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L381-L390
train
spyder-ide/spyder
spyder/widgets/calltip.py
CallTipWidget._cursor_position_changed
def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """ cursor = self._text_edit.textCursor() position = cursor.position() document = self._text_edit.document() char = to_text_string(document.characterAt(position - 1)) if position <= self._start_position: self.hide() elif char == ')': pos, _ = self._find_parenthesis(position - 1, forward=False) if pos == -1: self.hide()
python
def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """ cursor = self._text_edit.textCursor() position = cursor.position() document = self._text_edit.document() char = to_text_string(document.characterAt(position - 1)) if position <= self._start_position: self.hide() elif char == ')': pos, _ = self._find_parenthesis(position - 1, forward=False) if pos == -1: self.hide()
[ "def", "_cursor_position_changed", "(", "self", ")", ":", "cursor", "=", "self", ".", "_text_edit", ".", "textCursor", "(", ")", "position", "=", "cursor", ".", "position", "(", ")", "document", "=", "self", ".", "_text_edit", ".", "document", "(", ")", "char", "=", "to_text_string", "(", "document", ".", "characterAt", "(", "position", "-", "1", ")", ")", "if", "position", "<=", "self", ".", "_start_position", ":", "self", ".", "hide", "(", ")", "elif", "char", "==", "')'", ":", "pos", ",", "_", "=", "self", ".", "_find_parenthesis", "(", "position", "-", "1", ",", "forward", "=", "False", ")", "if", "pos", "==", "-", "1", ":", "self", ".", "hide", "(", ")" ]
Updates the tip based on user cursor movement.
[ "Updates", "the", "tip", "based", "on", "user", "cursor", "movement", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L394-L406
train
spyder-ide/spyder
spyder/utils/sourcecode.py
has_mixed_eol_chars
def has_mixed_eol_chars(text): """Detect if text has mixed EOL characters""" eol_chars = get_eol_chars(text) if eol_chars is None: return False correct_text = eol_chars.join((text+eol_chars).splitlines()) return repr(correct_text) != repr(text)
python
def has_mixed_eol_chars(text): """Detect if text has mixed EOL characters""" eol_chars = get_eol_chars(text) if eol_chars is None: return False correct_text = eol_chars.join((text+eol_chars).splitlines()) return repr(correct_text) != repr(text)
[ "def", "has_mixed_eol_chars", "(", "text", ")", ":", "eol_chars", "=", "get_eol_chars", "(", "text", ")", "if", "eol_chars", "is", "None", ":", "return", "False", "correct_text", "=", "eol_chars", ".", "join", "(", "(", "text", "+", "eol_chars", ")", ".", "splitlines", "(", ")", ")", "return", "repr", "(", "correct_text", ")", "!=", "repr", "(", "text", ")" ]
Detect if text has mixed EOL characters
[ "Detect", "if", "text", "has", "mixed", "EOL", "characters" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L44-L50
train
spyder-ide/spyder
spyder/utils/sourcecode.py
normalize_eols
def normalize_eols(text, eol='\n'): """Use the same eol's in text""" for eol_char, _ in EOL_CHARS: if eol_char != eol: text = text.replace(eol_char, eol) return text
python
def normalize_eols(text, eol='\n'): """Use the same eol's in text""" for eol_char, _ in EOL_CHARS: if eol_char != eol: text = text.replace(eol_char, eol) return text
[ "def", "normalize_eols", "(", "text", ",", "eol", "=", "'\\n'", ")", ":", "for", "eol_char", ",", "_", "in", "EOL_CHARS", ":", "if", "eol_char", "!=", "eol", ":", "text", "=", "text", ".", "replace", "(", "eol_char", ",", "eol", ")", "return", "text" ]
Use the same eol's in text
[ "Use", "the", "same", "eol", "s", "in", "text" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L53-L58
train
spyder-ide/spyder
spyder/utils/sourcecode.py
is_builtin
def is_builtin(text): """Test if passed string is the name of a Python builtin object""" from spyder.py3compat import builtins return text in [str(name) for name in dir(builtins) if not name.startswith('_')]
python
def is_builtin(text): """Test if passed string is the name of a Python builtin object""" from spyder.py3compat import builtins return text in [str(name) for name in dir(builtins) if not name.startswith('_')]
[ "def", "is_builtin", "(", "text", ")", ":", "from", "spyder", ".", "py3compat", "import", "builtins", "return", "text", "in", "[", "str", "(", "name", ")", "for", "name", "in", "dir", "(", "builtins", ")", "if", "not", "name", ".", "startswith", "(", "'_'", ")", "]" ]
Test if passed string is the name of a Python builtin object
[ "Test", "if", "passed", "string", "is", "the", "name", "of", "a", "Python", "builtin", "object" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L66-L70
train
spyder-ide/spyder
spyder/utils/sourcecode.py
get_primary_at
def get_primary_at(source_code, offset, retry=True): """Return Python object in *source_code* at *offset* Periods to the left of the cursor are carried forward e.g. 'functools.par^tial' would yield 'functools.partial' Retry prevents infinite recursion: retry only once """ obj = '' left = re.split(r"[^0-9a-zA-Z_.]", source_code[:offset]) if left and left[-1]: obj = left[-1] right = re.split(r"\W", source_code[offset:]) if right and right[0]: obj += right[0] if obj and obj[0].isdigit(): obj = '' # account for opening chars with no text to the right if not obj and retry and offset and source_code[offset - 1] in '([.': return get_primary_at(source_code, offset - 1, retry=False) return obj
python
def get_primary_at(source_code, offset, retry=True): """Return Python object in *source_code* at *offset* Periods to the left of the cursor are carried forward e.g. 'functools.par^tial' would yield 'functools.partial' Retry prevents infinite recursion: retry only once """ obj = '' left = re.split(r"[^0-9a-zA-Z_.]", source_code[:offset]) if left and left[-1]: obj = left[-1] right = re.split(r"\W", source_code[offset:]) if right and right[0]: obj += right[0] if obj and obj[0].isdigit(): obj = '' # account for opening chars with no text to the right if not obj and retry and offset and source_code[offset - 1] in '([.': return get_primary_at(source_code, offset - 1, retry=False) return obj
[ "def", "get_primary_at", "(", "source_code", ",", "offset", ",", "retry", "=", "True", ")", ":", "obj", "=", "''", "left", "=", "re", ".", "split", "(", "r\"[^0-9a-zA-Z_.]\"", ",", "source_code", "[", ":", "offset", "]", ")", "if", "left", "and", "left", "[", "-", "1", "]", ":", "obj", "=", "left", "[", "-", "1", "]", "right", "=", "re", ".", "split", "(", "r\"\\W\"", ",", "source_code", "[", "offset", ":", "]", ")", "if", "right", "and", "right", "[", "0", "]", ":", "obj", "+=", "right", "[", "0", "]", "if", "obj", "and", "obj", "[", "0", "]", ".", "isdigit", "(", ")", ":", "obj", "=", "''", "# account for opening chars with no text to the right\r", "if", "not", "obj", "and", "retry", "and", "offset", "and", "source_code", "[", "offset", "-", "1", "]", "in", "'([.'", ":", "return", "get_primary_at", "(", "source_code", ",", "offset", "-", "1", ",", "retry", "=", "False", ")", "return", "obj" ]
Return Python object in *source_code* at *offset* Periods to the left of the cursor are carried forward e.g. 'functools.par^tial' would yield 'functools.partial' Retry prevents infinite recursion: retry only once
[ "Return", "Python", "object", "in", "*", "source_code", "*", "at", "*", "offset", "*", "Periods", "to", "the", "left", "of", "the", "cursor", "are", "carried", "forward", "e", ".", "g", ".", "functools", ".", "par^tial", "would", "yield", "functools", ".", "partial", "Retry", "prevents", "infinite", "recursion", ":", "retry", "only", "once" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L79-L97
train
spyder-ide/spyder
spyder/utils/sourcecode.py
split_source
def split_source(source_code): '''Split source code into lines ''' eol_chars = get_eol_chars(source_code) if eol_chars: return source_code.split(eol_chars) else: return [source_code]
python
def split_source(source_code): '''Split source code into lines ''' eol_chars = get_eol_chars(source_code) if eol_chars: return source_code.split(eol_chars) else: return [source_code]
[ "def", "split_source", "(", "source_code", ")", ":", "eol_chars", "=", "get_eol_chars", "(", "source_code", ")", "if", "eol_chars", ":", "return", "source_code", ".", "split", "(", "eol_chars", ")", "else", ":", "return", "[", "source_code", "]" ]
Split source code into lines
[ "Split", "source", "code", "into", "lines" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L100-L107
train
spyder-ide/spyder
spyder/utils/sourcecode.py
get_identifiers
def get_identifiers(source_code): '''Split source code into python identifier-like tokens''' tokens = set(re.split(r"[^0-9a-zA-Z_.]", source_code)) valid = re.compile(r'[a-zA-Z_]') return [token for token in tokens if re.match(valid, token)]
python
def get_identifiers(source_code): '''Split source code into python identifier-like tokens''' tokens = set(re.split(r"[^0-9a-zA-Z_.]", source_code)) valid = re.compile(r'[a-zA-Z_]') return [token for token in tokens if re.match(valid, token)]
[ "def", "get_identifiers", "(", "source_code", ")", ":", "tokens", "=", "set", "(", "re", ".", "split", "(", "r\"[^0-9a-zA-Z_.]\"", ",", "source_code", ")", ")", "valid", "=", "re", ".", "compile", "(", "r'[a-zA-Z_]'", ")", "return", "[", "token", "for", "token", "in", "tokens", "if", "re", ".", "match", "(", "valid", ",", "token", ")", "]" ]
Split source code into python identifier-like tokens
[ "Split", "source", "code", "into", "python", "identifier", "-", "like", "tokens" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L110-L114
train
spyder-ide/spyder
spyder/utils/sourcecode.py
path_components
def path_components(path): """ Return the individual components of a given file path string (for the local operating system). Taken from https://stackoverflow.com/q/21498939/438386 """ components = [] # The loop guarantees that the returned components can be # os.path.joined with the path separator and point to the same # location: while True: (new_path, tail) = os.path.split(path) # Works on any platform components.append(tail) if new_path == path: # Root (including drive, on Windows) reached break path = new_path components.append(new_path) components.reverse() # First component first return components
python
def path_components(path): """ Return the individual components of a given file path string (for the local operating system). Taken from https://stackoverflow.com/q/21498939/438386 """ components = [] # The loop guarantees that the returned components can be # os.path.joined with the path separator and point to the same # location: while True: (new_path, tail) = os.path.split(path) # Works on any platform components.append(tail) if new_path == path: # Root (including drive, on Windows) reached break path = new_path components.append(new_path) components.reverse() # First component first return components
[ "def", "path_components", "(", "path", ")", ":", "components", "=", "[", "]", "# The loop guarantees that the returned components can be\r", "# os.path.joined with the path separator and point to the same\r", "# location: \r", "while", "True", ":", "(", "new_path", ",", "tail", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "# Works on any platform\r", "components", ".", "append", "(", "tail", ")", "if", "new_path", "==", "path", ":", "# Root (including drive, on Windows) reached\r", "break", "path", "=", "new_path", "components", ".", "append", "(", "new_path", ")", "components", ".", "reverse", "(", ")", "# First component first \r", "return", "components" ]
Return the individual components of a given file path string (for the local operating system). Taken from https://stackoverflow.com/q/21498939/438386
[ "Return", "the", "individual", "components", "of", "a", "given", "file", "path", "string", "(", "for", "the", "local", "operating", "system", ")", ".", "Taken", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "q", "/", "21498939", "/", "438386" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L116-L135
train
spyder-ide/spyder
spyder/utils/sourcecode.py
differentiate_prefix
def differentiate_prefix(path_components0, path_components1): """ Return the differentiated prefix of the given two iterables. Taken from https://stackoverflow.com/q/21498939/438386 """ longest_prefix = [] root_comparison = False common_elmt = None for index, (elmt0, elmt1) in enumerate(zip(path_components0, path_components1)): if elmt0 != elmt1: if index == 2: root_comparison = True break else: common_elmt = elmt0 longest_prefix.append(elmt0) file_name_length = len(path_components0[len(path_components0) - 1]) path_0 = os.path.join(*path_components0)[:-file_name_length - 1] if len(longest_prefix) > 0: longest_path_prefix = os.path.join(*longest_prefix) longest_prefix_length = len(longest_path_prefix) + 1 if path_0[longest_prefix_length:] != '' and not root_comparison: path_0_components = path_components(path_0[longest_prefix_length:]) if path_0_components[0] == ''and path_0_components[1] == ''and len( path_0[longest_prefix_length:]) > 20: path_0_components.insert(2, common_elmt) path_0 = os.path.join(*path_0_components) else: path_0 = path_0[longest_prefix_length:] elif not root_comparison: path_0 = common_elmt elif sys.platform.startswith('linux') and path_0 == '': path_0 = '/' return path_0
python
def differentiate_prefix(path_components0, path_components1): """ Return the differentiated prefix of the given two iterables. Taken from https://stackoverflow.com/q/21498939/438386 """ longest_prefix = [] root_comparison = False common_elmt = None for index, (elmt0, elmt1) in enumerate(zip(path_components0, path_components1)): if elmt0 != elmt1: if index == 2: root_comparison = True break else: common_elmt = elmt0 longest_prefix.append(elmt0) file_name_length = len(path_components0[len(path_components0) - 1]) path_0 = os.path.join(*path_components0)[:-file_name_length - 1] if len(longest_prefix) > 0: longest_path_prefix = os.path.join(*longest_prefix) longest_prefix_length = len(longest_path_prefix) + 1 if path_0[longest_prefix_length:] != '' and not root_comparison: path_0_components = path_components(path_0[longest_prefix_length:]) if path_0_components[0] == ''and path_0_components[1] == ''and len( path_0[longest_prefix_length:]) > 20: path_0_components.insert(2, common_elmt) path_0 = os.path.join(*path_0_components) else: path_0 = path_0[longest_prefix_length:] elif not root_comparison: path_0 = common_elmt elif sys.platform.startswith('linux') and path_0 == '': path_0 = '/' return path_0
[ "def", "differentiate_prefix", "(", "path_components0", ",", "path_components1", ")", ":", "longest_prefix", "=", "[", "]", "root_comparison", "=", "False", "common_elmt", "=", "None", "for", "index", ",", "(", "elmt0", ",", "elmt1", ")", "in", "enumerate", "(", "zip", "(", "path_components0", ",", "path_components1", ")", ")", ":", "if", "elmt0", "!=", "elmt1", ":", "if", "index", "==", "2", ":", "root_comparison", "=", "True", "break", "else", ":", "common_elmt", "=", "elmt0", "longest_prefix", ".", "append", "(", "elmt0", ")", "file_name_length", "=", "len", "(", "path_components0", "[", "len", "(", "path_components0", ")", "-", "1", "]", ")", "path_0", "=", "os", ".", "path", ".", "join", "(", "*", "path_components0", ")", "[", ":", "-", "file_name_length", "-", "1", "]", "if", "len", "(", "longest_prefix", ")", ">", "0", ":", "longest_path_prefix", "=", "os", ".", "path", ".", "join", "(", "*", "longest_prefix", ")", "longest_prefix_length", "=", "len", "(", "longest_path_prefix", ")", "+", "1", "if", "path_0", "[", "longest_prefix_length", ":", "]", "!=", "''", "and", "not", "root_comparison", ":", "path_0_components", "=", "path_components", "(", "path_0", "[", "longest_prefix_length", ":", "]", ")", "if", "path_0_components", "[", "0", "]", "==", "''", "and", "path_0_components", "[", "1", "]", "==", "''", "and", "len", "(", "path_0", "[", "longest_prefix_length", ":", "]", ")", ">", "20", ":", "path_0_components", ".", "insert", "(", "2", ",", "common_elmt", ")", "path_0", "=", "os", ".", "path", ".", "join", "(", "*", "path_0_components", ")", "else", ":", "path_0", "=", "path_0", "[", "longest_prefix_length", ":", "]", "elif", "not", "root_comparison", ":", "path_0", "=", "common_elmt", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", "and", "path_0", "==", "''", ":", "path_0", "=", "'/'", "return", "path_0" ]
Return the differentiated prefix of the given two iterables. Taken from https://stackoverflow.com/q/21498939/438386
[ "Return", "the", "differentiated", "prefix", "of", "the", "given", "two", "iterables", ".", "Taken", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "q", "/", "21498939", "/", "438386" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L137-L171
train
spyder-ide/spyder
spyder/utils/sourcecode.py
disambiguate_fname
def disambiguate_fname(files_path_list, filename): """Get tab title without ambiguation.""" fname = os.path.basename(filename) same_name_files = get_same_name_files(files_path_list, fname) if len(same_name_files) > 1: compare_path = shortest_path(same_name_files) if compare_path == filename: same_name_files.remove(path_components(filename)) compare_path = shortest_path(same_name_files) diff_path = differentiate_prefix(path_components(filename), path_components(compare_path)) diff_path_length = len(diff_path) path_component = path_components(diff_path) if (diff_path_length > 20 and len(path_component) > 2): if path_component[0] != '/' and path_component[0] != '': path_component = [path_component[0], '...', path_component[-1]] else: path_component = [path_component[2], '...', path_component[-1]] diff_path = os.path.join(*path_component) fname = fname + " - " + diff_path return fname
python
def disambiguate_fname(files_path_list, filename): """Get tab title without ambiguation.""" fname = os.path.basename(filename) same_name_files = get_same_name_files(files_path_list, fname) if len(same_name_files) > 1: compare_path = shortest_path(same_name_files) if compare_path == filename: same_name_files.remove(path_components(filename)) compare_path = shortest_path(same_name_files) diff_path = differentiate_prefix(path_components(filename), path_components(compare_path)) diff_path_length = len(diff_path) path_component = path_components(diff_path) if (diff_path_length > 20 and len(path_component) > 2): if path_component[0] != '/' and path_component[0] != '': path_component = [path_component[0], '...', path_component[-1]] else: path_component = [path_component[2], '...', path_component[-1]] diff_path = os.path.join(*path_component) fname = fname + " - " + diff_path return fname
[ "def", "disambiguate_fname", "(", "files_path_list", ",", "filename", ")", ":", "fname", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "same_name_files", "=", "get_same_name_files", "(", "files_path_list", ",", "fname", ")", "if", "len", "(", "same_name_files", ")", ">", "1", ":", "compare_path", "=", "shortest_path", "(", "same_name_files", ")", "if", "compare_path", "==", "filename", ":", "same_name_files", ".", "remove", "(", "path_components", "(", "filename", ")", ")", "compare_path", "=", "shortest_path", "(", "same_name_files", ")", "diff_path", "=", "differentiate_prefix", "(", "path_components", "(", "filename", ")", ",", "path_components", "(", "compare_path", ")", ")", "diff_path_length", "=", "len", "(", "diff_path", ")", "path_component", "=", "path_components", "(", "diff_path", ")", "if", "(", "diff_path_length", ">", "20", "and", "len", "(", "path_component", ")", ">", "2", ")", ":", "if", "path_component", "[", "0", "]", "!=", "'/'", "and", "path_component", "[", "0", "]", "!=", "''", ":", "path_component", "=", "[", "path_component", "[", "0", "]", ",", "'...'", ",", "path_component", "[", "-", "1", "]", "]", "else", ":", "path_component", "=", "[", "path_component", "[", "2", "]", ",", "'...'", ",", "path_component", "[", "-", "1", "]", "]", "diff_path", "=", "os", ".", "path", ".", "join", "(", "*", "path_component", ")", "fname", "=", "fname", "+", "\" - \"", "+", "diff_path", "return", "fname" ]
Get tab title without ambiguation.
[ "Get", "tab", "title", "without", "ambiguation", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L173-L195
train
spyder-ide/spyder
spyder/utils/sourcecode.py
get_same_name_files
def get_same_name_files(files_path_list, filename): """Get a list of the path components of the files with the same name.""" same_name_files = [] for fname in files_path_list: if filename == os.path.basename(fname): same_name_files.append(path_components(fname)) return same_name_files
python
def get_same_name_files(files_path_list, filename): """Get a list of the path components of the files with the same name.""" same_name_files = [] for fname in files_path_list: if filename == os.path.basename(fname): same_name_files.append(path_components(fname)) return same_name_files
[ "def", "get_same_name_files", "(", "files_path_list", ",", "filename", ")", ":", "same_name_files", "=", "[", "]", "for", "fname", "in", "files_path_list", ":", "if", "filename", "==", "os", ".", "path", ".", "basename", "(", "fname", ")", ":", "same_name_files", ".", "append", "(", "path_components", "(", "fname", ")", ")", "return", "same_name_files" ]
Get a list of the path components of the files with the same name.
[ "Get", "a", "list", "of", "the", "path", "components", "of", "the", "files", "with", "the", "same", "name", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L197-L203
train
spyder-ide/spyder
spyder/plugins/editor/utils/decoration.py
TextDecorationsManager.add
def add(self, decorations): """ Add text decorations on a CodeEditor instance. Don't add duplicated decorations, and order decorations according draw_order and the size of the selection. Args: decorations (sourcecode.api.TextDecoration) (could be a list) Returns: int: Amount of decorations added. """ added = 0 if isinstance(decorations, list): not_repeated = set(decorations) - set(self._decorations) self._decorations.extend(list(not_repeated)) added = len(not_repeated) elif decorations not in self._decorations: self._decorations.append(decorations) added = 1 if added > 0: self._order_decorations() self.update() return added
python
def add(self, decorations): """ Add text decorations on a CodeEditor instance. Don't add duplicated decorations, and order decorations according draw_order and the size of the selection. Args: decorations (sourcecode.api.TextDecoration) (could be a list) Returns: int: Amount of decorations added. """ added = 0 if isinstance(decorations, list): not_repeated = set(decorations) - set(self._decorations) self._decorations.extend(list(not_repeated)) added = len(not_repeated) elif decorations not in self._decorations: self._decorations.append(decorations) added = 1 if added > 0: self._order_decorations() self.update() return added
[ "def", "add", "(", "self", ",", "decorations", ")", ":", "added", "=", "0", "if", "isinstance", "(", "decorations", ",", "list", ")", ":", "not_repeated", "=", "set", "(", "decorations", ")", "-", "set", "(", "self", ".", "_decorations", ")", "self", ".", "_decorations", ".", "extend", "(", "list", "(", "not_repeated", ")", ")", "added", "=", "len", "(", "not_repeated", ")", "elif", "decorations", "not", "in", "self", ".", "_decorations", ":", "self", ".", "_decorations", ".", "append", "(", "decorations", ")", "added", "=", "1", "if", "added", ">", "0", ":", "self", ".", "_order_decorations", "(", ")", "self", ".", "update", "(", ")", "return", "added" ]
Add text decorations on a CodeEditor instance. Don't add duplicated decorations, and order decorations according draw_order and the size of the selection. Args: decorations (sourcecode.api.TextDecoration) (could be a list) Returns: int: Amount of decorations added.
[ "Add", "text", "decorations", "on", "a", "CodeEditor", "instance", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/decoration.py#L35-L59
train
spyder-ide/spyder
spyder/plugins/editor/utils/decoration.py
TextDecorationsManager.remove
def remove(self, decoration): """ Removes a text decoration from the editor. :param decoration: Text decoration to remove :type decoration: spyder.api.TextDecoration """ try: self._decorations.remove(decoration) self.update() return True except ValueError: return False except RuntimeError: # This is needed to fix issue 9173 pass
python
def remove(self, decoration): """ Removes a text decoration from the editor. :param decoration: Text decoration to remove :type decoration: spyder.api.TextDecoration """ try: self._decorations.remove(decoration) self.update() return True except ValueError: return False except RuntimeError: # This is needed to fix issue 9173 pass
[ "def", "remove", "(", "self", ",", "decoration", ")", ":", "try", ":", "self", ".", "_decorations", ".", "remove", "(", "decoration", ")", "self", ".", "update", "(", ")", "return", "True", "except", "ValueError", ":", "return", "False", "except", "RuntimeError", ":", "# This is needed to fix issue 9173", "pass" ]
Removes a text decoration from the editor. :param decoration: Text decoration to remove :type decoration: spyder.api.TextDecoration
[ "Removes", "a", "text", "decoration", "from", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/decoration.py#L61-L76
train
spyder-ide/spyder
spyder/plugins/editor/utils/decoration.py
TextDecorationsManager.update
def update(self): """Update editor extra selections with added decorations. NOTE: Update TextDecorations to use editor font, using a different font family and point size could cause unwanted behaviors. """ font = self.editor.font() for decoration in self._decorations: try: decoration.format.setFont( font, QTextCharFormat.FontPropertiesSpecifiedOnly) except (TypeError, AttributeError): # Qt < 5.3 decoration.format.setFontFamily(font.family()) decoration.format.setFontPointSize(font.pointSize()) self.editor.setExtraSelections(self._decorations)
python
def update(self): """Update editor extra selections with added decorations. NOTE: Update TextDecorations to use editor font, using a different font family and point size could cause unwanted behaviors. """ font = self.editor.font() for decoration in self._decorations: try: decoration.format.setFont( font, QTextCharFormat.FontPropertiesSpecifiedOnly) except (TypeError, AttributeError): # Qt < 5.3 decoration.format.setFontFamily(font.family()) decoration.format.setFontPointSize(font.pointSize()) self.editor.setExtraSelections(self._decorations)
[ "def", "update", "(", "self", ")", ":", "font", "=", "self", ".", "editor", ".", "font", "(", ")", "for", "decoration", "in", "self", ".", "_decorations", ":", "try", ":", "decoration", ".", "format", ".", "setFont", "(", "font", ",", "QTextCharFormat", ".", "FontPropertiesSpecifiedOnly", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "# Qt < 5.3", "decoration", ".", "format", ".", "setFontFamily", "(", "font", ".", "family", "(", ")", ")", "decoration", ".", "format", ".", "setFontPointSize", "(", "font", ".", "pointSize", "(", ")", ")", "self", ".", "editor", ".", "setExtraSelections", "(", "self", ".", "_decorations", ")" ]
Update editor extra selections with added decorations. NOTE: Update TextDecorations to use editor font, using a different font family and point size could cause unwanted behaviors.
[ "Update", "editor", "extra", "selections", "with", "added", "decorations", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/decoration.py#L86-L100
train
spyder-ide/spyder
spyder/plugins/editor/utils/decoration.py
TextDecorationsManager._order_decorations
def _order_decorations(self): """Order decorations according draw_order and size of selection. Highest draw_order will appear on top of the lowest values. If draw_order is equal,smaller selections are draw in top of bigger selections. """ def order_function(sel): end = sel.cursor.selectionEnd() start = sel.cursor.selectionStart() return sel.draw_order, -(end - start) self._decorations = sorted(self._decorations, key=order_function)
python
def _order_decorations(self): """Order decorations according draw_order and size of selection. Highest draw_order will appear on top of the lowest values. If draw_order is equal,smaller selections are draw in top of bigger selections. """ def order_function(sel): end = sel.cursor.selectionEnd() start = sel.cursor.selectionStart() return sel.draw_order, -(end - start) self._decorations = sorted(self._decorations, key=order_function)
[ "def", "_order_decorations", "(", "self", ")", ":", "def", "order_function", "(", "sel", ")", ":", "end", "=", "sel", ".", "cursor", ".", "selectionEnd", "(", ")", "start", "=", "sel", ".", "cursor", ".", "selectionStart", "(", ")", "return", "sel", ".", "draw_order", ",", "-", "(", "end", "-", "start", ")", "self", ".", "_decorations", "=", "sorted", "(", "self", ".", "_decorations", ",", "key", "=", "order_function", ")" ]
Order decorations according draw_order and size of selection. Highest draw_order will appear on top of the lowest values. If draw_order is equal,smaller selections are draw in top of bigger selections.
[ "Order", "decorations", "according", "draw_order", "and", "size", "of", "selection", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/decoration.py#L108-L122
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/help.py
HelpWidget.get_signature
def get_signature(self, content): """Get signature from inspect reply content""" data = content.get('data', {}) text = data.get('text/plain', '') if text: text = ANSI_OR_SPECIAL_PATTERN.sub('', text) self._control.current_prompt_pos = self._prompt_pos line = self._control.get_current_line_to_cursor() name = line[:-1].split('(')[-1] # Take last token after a ( name = name.split('.')[-1] # Then take last token after a . # Clean name from invalid chars try: name = self.clean_invalid_var_chars(name).split('_')[-1] except: pass argspec = getargspecfromtext(text) if argspec: # This covers cases like np.abs, whose docstring is # the same as np.absolute and because of that a proper # signature can't be obtained correctly signature = name + argspec else: signature = getsignaturefromtext(text, name) # Remove docstring for uniformity with editor signature = signature.split('Docstring:')[0] return signature else: return ''
python
def get_signature(self, content): """Get signature from inspect reply content""" data = content.get('data', {}) text = data.get('text/plain', '') if text: text = ANSI_OR_SPECIAL_PATTERN.sub('', text) self._control.current_prompt_pos = self._prompt_pos line = self._control.get_current_line_to_cursor() name = line[:-1].split('(')[-1] # Take last token after a ( name = name.split('.')[-1] # Then take last token after a . # Clean name from invalid chars try: name = self.clean_invalid_var_chars(name).split('_')[-1] except: pass argspec = getargspecfromtext(text) if argspec: # This covers cases like np.abs, whose docstring is # the same as np.absolute and because of that a proper # signature can't be obtained correctly signature = name + argspec else: signature = getsignaturefromtext(text, name) # Remove docstring for uniformity with editor signature = signature.split('Docstring:')[0] return signature else: return ''
[ "def", "get_signature", "(", "self", ",", "content", ")", ":", "data", "=", "content", ".", "get", "(", "'data'", ",", "{", "}", ")", "text", "=", "data", ".", "get", "(", "'text/plain'", ",", "''", ")", "if", "text", ":", "text", "=", "ANSI_OR_SPECIAL_PATTERN", ".", "sub", "(", "''", ",", "text", ")", "self", ".", "_control", ".", "current_prompt_pos", "=", "self", ".", "_prompt_pos", "line", "=", "self", ".", "_control", ".", "get_current_line_to_cursor", "(", ")", "name", "=", "line", "[", ":", "-", "1", "]", ".", "split", "(", "'('", ")", "[", "-", "1", "]", "# Take last token after a (", "name", "=", "name", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "# Then take last token after a .", "# Clean name from invalid chars", "try", ":", "name", "=", "self", ".", "clean_invalid_var_chars", "(", "name", ")", ".", "split", "(", "'_'", ")", "[", "-", "1", "]", "except", ":", "pass", "argspec", "=", "getargspecfromtext", "(", "text", ")", "if", "argspec", ":", "# This covers cases like np.abs, whose docstring is", "# the same as np.absolute and because of that a proper", "# signature can't be obtained correctly", "signature", "=", "name", "+", "argspec", "else", ":", "signature", "=", "getsignaturefromtext", "(", "text", ",", "name", ")", "# Remove docstring for uniformity with editor", "signature", "=", "signature", ".", "split", "(", "'Docstring:'", ")", "[", "0", "]", "return", "signature", "else", ":", "return", "''" ]
Get signature from inspect reply content
[ "Get", "signature", "from", "inspect", "reply", "content" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/help.py#L40-L69
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/help.py
HelpWidget.is_defined
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method( "get_ipython().kernel.is_defined('%s', force_import=%s)" % (objtxt, force_import)) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
python
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method( "get_ipython().kernel.is_defined('%s', force_import=%s)" % (objtxt, force_import)) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
[ "def", "is_defined", "(", "self", ",", "objtxt", ",", "force_import", "=", "False", ")", ":", "if", "self", ".", "_reading", ":", "return", "wait_loop", "=", "QEventLoop", "(", ")", "self", ".", "sig_got_reply", ".", "connect", "(", "wait_loop", ".", "quit", ")", "self", ".", "silent_exec_method", "(", "\"get_ipython().kernel.is_defined('%s', force_import=%s)\"", "%", "(", "objtxt", ",", "force_import", ")", ")", "wait_loop", ".", "exec_", "(", ")", "# Remove loop connection and loop", "self", ".", "sig_got_reply", ".", "disconnect", "(", "wait_loop", ".", "quit", ")", "wait_loop", "=", "None", "return", "self", ".", "_kernel_reply" ]
Return True if object is defined
[ "Return", "True", "if", "object", "is", "defined" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/help.py#L71-L86
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/help.py
HelpWidget.get_doc
def get_doc(self, objtxt): """Get object documentation dictionary""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
python
def get_doc(self, objtxt): """Get object documentation dictionary""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None return self._kernel_reply
[ "def", "get_doc", "(", "self", ",", "objtxt", ")", ":", "if", "self", ".", "_reading", ":", "return", "wait_loop", "=", "QEventLoop", "(", ")", "self", ".", "sig_got_reply", ".", "connect", "(", "wait_loop", ".", "quit", ")", "self", ".", "silent_exec_method", "(", "\"get_ipython().kernel.get_doc('%s')\"", "%", "objtxt", ")", "wait_loop", ".", "exec_", "(", ")", "# Remove loop connection and loop", "self", ".", "sig_got_reply", ".", "disconnect", "(", "wait_loop", ".", "quit", ")", "wait_loop", "=", "None", "return", "self", ".", "_kernel_reply" ]
Get object documentation dictionary
[ "Get", "object", "documentation", "dictionary" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/help.py#L88-L101
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/help.py
HelpWidget._handle_inspect_reply
def _handle_inspect_reply(self, rep): """ Reimplement call tips to only show signatures, using the same style from our Editor and External Console too """ cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] if content.get('status') == 'ok' and content.get('found', False): signature = self.get_signature(content) if signature: # TODO: Pass the language from the Console to the calltip self._control.show_calltip(signature, color='#999999', is_python=True)
python
def _handle_inspect_reply(self, rep): """ Reimplement call tips to only show signatures, using the same style from our Editor and External Console too """ cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] if content.get('status') == 'ok' and content.get('found', False): signature = self.get_signature(content) if signature: # TODO: Pass the language from the Console to the calltip self._control.show_calltip(signature, color='#999999', is_python=True)
[ "def", "_handle_inspect_reply", "(", "self", ",", "rep", ")", ":", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "info", "=", "self", ".", "_request_info", ".", "get", "(", "'call_tip'", ")", "if", "info", "and", "info", ".", "id", "==", "rep", "[", "'parent_header'", "]", "[", "'msg_id'", "]", "and", "info", ".", "pos", "==", "cursor", ".", "position", "(", ")", ":", "content", "=", "rep", "[", "'content'", "]", "if", "content", ".", "get", "(", "'status'", ")", "==", "'ok'", "and", "content", ".", "get", "(", "'found'", ",", "False", ")", ":", "signature", "=", "self", ".", "get_signature", "(", "content", ")", "if", "signature", ":", "# TODO: Pass the language from the Console to the calltip", "self", ".", "_control", ".", "show_calltip", "(", "signature", ",", "color", "=", "'#999999'", ",", "is_python", "=", "True", ")" ]
Reimplement call tips to only show signatures, using the same style from our Editor and External Console too
[ "Reimplement", "call", "tips", "to", "only", "show", "signatures", "using", "the", "same", "style", "from", "our", "Editor", "and", "External", "Console", "too" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/help.py#L119-L134
train
spyder-ide/spyder
spyder/utils/external/github.py
_encode_params
def _encode_params(kw): ''' Encode parameters. ''' args = [] for k, v in kw.items(): try: # Python 2 qv = v.encode('utf-8') if isinstance(v, unicode) else str(v) except: qv = v args.append('%s=%s' % (k, urlquote(qv))) return '&'.join(args)
python
def _encode_params(kw): ''' Encode parameters. ''' args = [] for k, v in kw.items(): try: # Python 2 qv = v.encode('utf-8') if isinstance(v, unicode) else str(v) except: qv = v args.append('%s=%s' % (k, urlquote(qv))) return '&'.join(args)
[ "def", "_encode_params", "(", "kw", ")", ":", "args", "=", "[", "]", "for", "k", ",", "v", "in", "kw", ".", "items", "(", ")", ":", "try", ":", "# Python 2", "qv", "=", "v", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "v", ",", "unicode", ")", "else", "str", "(", "v", ")", "except", ":", "qv", "=", "v", "args", ".", "append", "(", "'%s=%s'", "%", "(", "k", ",", "urlquote", "(", "qv", ")", ")", ")", "return", "'&'", ".", "join", "(", "args", ")" ]
Encode parameters.
[ "Encode", "parameters", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/github.py#L79-L91
train
spyder-ide/spyder
spyder/utils/external/github.py
_encode_json
def _encode_json(obj): ''' Encode object as json str. ''' def _dump_obj(obj): if isinstance(obj, dict): return obj d = dict() for k in dir(obj): if not k.startswith('_'): d[k] = getattr(obj, k) return d return json.dumps(obj, default=_dump_obj)
python
def _encode_json(obj): ''' Encode object as json str. ''' def _dump_obj(obj): if isinstance(obj, dict): return obj d = dict() for k in dir(obj): if not k.startswith('_'): d[k] = getattr(obj, k) return d return json.dumps(obj, default=_dump_obj)
[ "def", "_encode_json", "(", "obj", ")", ":", "def", "_dump_obj", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "obj", "d", "=", "dict", "(", ")", "for", "k", "in", "dir", "(", "obj", ")", ":", "if", "not", "k", ".", "startswith", "(", "'_'", ")", ":", "d", "[", "k", "]", "=", "getattr", "(", "obj", ",", "k", ")", "return", "d", "return", "json", ".", "dumps", "(", "obj", ",", "default", "=", "_dump_obj", ")" ]
Encode object as json str.
[ "Encode", "object", "as", "json", "str", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/github.py#L93-L105
train
spyder-ide/spyder
spyder/utils/external/github.py
GitHub.authorize_url
def authorize_url(self, state=None): ''' Generate authorize_url. >>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url() 'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75' ''' if not self._client_id: raise ApiAuthError('No client id.') kw = dict(client_id=self._client_id) if self._redirect_uri: kw['redirect_uri'] = self._redirect_uri if self._scope: kw['scope'] = self._scope if state: kw['state'] = state return 'https://github.com/login/oauth/authorize?%s' % _encode_params(kw)
python
def authorize_url(self, state=None): ''' Generate authorize_url. >>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url() 'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75' ''' if not self._client_id: raise ApiAuthError('No client id.') kw = dict(client_id=self._client_id) if self._redirect_uri: kw['redirect_uri'] = self._redirect_uri if self._scope: kw['scope'] = self._scope if state: kw['state'] = state return 'https://github.com/login/oauth/authorize?%s' % _encode_params(kw)
[ "def", "authorize_url", "(", "self", ",", "state", "=", "None", ")", ":", "if", "not", "self", ".", "_client_id", ":", "raise", "ApiAuthError", "(", "'No client id.'", ")", "kw", "=", "dict", "(", "client_id", "=", "self", ".", "_client_id", ")", "if", "self", ".", "_redirect_uri", ":", "kw", "[", "'redirect_uri'", "]", "=", "self", ".", "_redirect_uri", "if", "self", ".", "_scope", ":", "kw", "[", "'scope'", "]", "=", "self", ".", "_scope", "if", "state", ":", "kw", "[", "'state'", "]", "=", "state", "return", "'https://github.com/login/oauth/authorize?%s'", "%", "_encode_params", "(", "kw", ")" ]
Generate authorize_url. >>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url() 'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75'
[ "Generate", "authorize_url", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/github.py#L184-L200
train
spyder-ide/spyder
spyder/utils/external/github.py
GitHub.get_access_token
def get_access_token(self, code, state=None): ''' In callback url: http://host/callback?code=123&state=xyz use code and state to get an access token. ''' kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code) if self._redirect_uri: kw['redirect_uri'] = self._redirect_uri if state: kw['state'] = state opener = build_opener(HTTPSHandler) request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw)) request.get_method = _METHOD_MAP['POST'] request.add_header('Accept', 'application/json') try: response = opener.open(request, timeout=TIMEOUT) r = _parse_json(response.read()) if 'error' in r: raise ApiAuthError(str(r.error)) return str(r.access_token) except HTTPError as e: raise ApiAuthError('HTTPError when get access token')
python
def get_access_token(self, code, state=None): ''' In callback url: http://host/callback?code=123&state=xyz use code and state to get an access token. ''' kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code) if self._redirect_uri: kw['redirect_uri'] = self._redirect_uri if state: kw['state'] = state opener = build_opener(HTTPSHandler) request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw)) request.get_method = _METHOD_MAP['POST'] request.add_header('Accept', 'application/json') try: response = opener.open(request, timeout=TIMEOUT) r = _parse_json(response.read()) if 'error' in r: raise ApiAuthError(str(r.error)) return str(r.access_token) except HTTPError as e: raise ApiAuthError('HTTPError when get access token')
[ "def", "get_access_token", "(", "self", ",", "code", ",", "state", "=", "None", ")", ":", "kw", "=", "dict", "(", "client_id", "=", "self", ".", "_client_id", ",", "client_secret", "=", "self", ".", "_client_secret", ",", "code", "=", "code", ")", "if", "self", ".", "_redirect_uri", ":", "kw", "[", "'redirect_uri'", "]", "=", "self", ".", "_redirect_uri", "if", "state", ":", "kw", "[", "'state'", "]", "=", "state", "opener", "=", "build_opener", "(", "HTTPSHandler", ")", "request", "=", "Request", "(", "'https://github.com/login/oauth/access_token'", ",", "data", "=", "_encode_params", "(", "kw", ")", ")", "request", ".", "get_method", "=", "_METHOD_MAP", "[", "'POST'", "]", "request", ".", "add_header", "(", "'Accept'", ",", "'application/json'", ")", "try", ":", "response", "=", "opener", ".", "open", "(", "request", ",", "timeout", "=", "TIMEOUT", ")", "r", "=", "_parse_json", "(", "response", ".", "read", "(", ")", ")", "if", "'error'", "in", "r", ":", "raise", "ApiAuthError", "(", "str", "(", "r", ".", "error", ")", ")", "return", "str", "(", "r", ".", "access_token", ")", "except", "HTTPError", "as", "e", ":", "raise", "ApiAuthError", "(", "'HTTPError when get access token'", ")" ]
In callback url: http://host/callback?code=123&state=xyz use code and state to get an access token.
[ "In", "callback", "url", ":", "http", ":", "//", "host", "/", "callback?code", "=", "123&state", "=", "xyz" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/github.py#L202-L224
train
spyder-ide/spyder
spyder/plugins/editor/lsp/decorators.py
send_request
def send_request(req=None, method=None, requires_response=True): """Call function req and then send its results via ZMQ.""" if req is None: return functools.partial(send_request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapper(self, *args, **kwargs): params = req(self, *args, **kwargs) _id = self.send(method, params, requires_response) return _id wrapper._sends = method return wrapper
python
def send_request(req=None, method=None, requires_response=True): """Call function req and then send its results via ZMQ.""" if req is None: return functools.partial(send_request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapper(self, *args, **kwargs): params = req(self, *args, **kwargs) _id = self.send(method, params, requires_response) return _id wrapper._sends = method return wrapper
[ "def", "send_request", "(", "req", "=", "None", ",", "method", "=", "None", ",", "requires_response", "=", "True", ")", ":", "if", "req", "is", "None", ":", "return", "functools", ".", "partial", "(", "send_request", ",", "method", "=", "method", ",", "requires_response", "=", "requires_response", ")", "@", "functools", ".", "wraps", "(", "req", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "req", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "_id", "=", "self", ".", "send", "(", "method", ",", "params", ",", "requires_response", ")", "return", "_id", "wrapper", ".", "_sends", "=", "method", "return", "wrapper" ]
Call function req and then send its results via ZMQ.
[ "Call", "function", "req", "and", "then", "send", "its", "results", "via", "ZMQ", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/lsp/decorators.py#L12-L24
train
spyder-ide/spyder
spyder/plugins/editor/lsp/decorators.py
class_register
def class_register(cls): """Class decorator that allows to map LSP method names to class methods.""" cls.handler_registry = {} cls.sender_registry = {} for method_name in dir(cls): method = getattr(cls, method_name) if hasattr(method, '_handle'): cls.handler_registry.update({method._handle: method_name}) if hasattr(method, '_sends'): cls.sender_registry.update({method._sends: method_name}) return cls
python
def class_register(cls): """Class decorator that allows to map LSP method names to class methods.""" cls.handler_registry = {} cls.sender_registry = {} for method_name in dir(cls): method = getattr(cls, method_name) if hasattr(method, '_handle'): cls.handler_registry.update({method._handle: method_name}) if hasattr(method, '_sends'): cls.sender_registry.update({method._sends: method_name}) return cls
[ "def", "class_register", "(", "cls", ")", ":", "cls", ".", "handler_registry", "=", "{", "}", "cls", ".", "sender_registry", "=", "{", "}", "for", "method_name", "in", "dir", "(", "cls", ")", ":", "method", "=", "getattr", "(", "cls", ",", "method_name", ")", "if", "hasattr", "(", "method", ",", "'_handle'", ")", ":", "cls", ".", "handler_registry", ".", "update", "(", "{", "method", ".", "_handle", ":", "method_name", "}", ")", "if", "hasattr", "(", "method", ",", "'_sends'", ")", ":", "cls", ".", "sender_registry", ".", "update", "(", "{", "method", ".", "_sends", ":", "method_name", "}", ")", "return", "cls" ]
Class decorator that allows to map LSP method names to class methods.
[ "Class", "decorator", "that", "allows", "to", "map", "LSP", "method", "names", "to", "class", "methods", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/lsp/decorators.py#L27-L37
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.set_data
def set_data(self, data, coll_filter=None): """Set model data""" self._data = data data_type = get_type_string(data) if coll_filter is not None and not self.remote and \ isinstance(data, (tuple, list, dict, set)): data = coll_filter(data) self.showndata = data self.header0 = _("Index") if self.names: self.header0 = _("Name") if isinstance(data, tuple): self.keys = list(range(len(data))) self.title += _("Tuple") elif isinstance(data, list): self.keys = list(range(len(data))) self.title += _("List") elif isinstance(data, set): self.keys = list(range(len(data))) self.title += _("Set") self._data = list(data) elif isinstance(data, dict): self.keys = list(data.keys()) self.title += _("Dictionary") if not self.names: self.header0 = _("Key") else: self.keys = get_object_attrs(data) self._data = data = self.showndata = ProxyObject(data) if not self.names: self.header0 = _("Attribute") if not isinstance(self._data, ProxyObject): self.title += (' (' + str(len(self.keys)) + ' ' + _("elements") + ')') else: self.title += data_type self.total_rows = len(self.keys) if self.total_rows > LARGE_NROWS: self.rows_loaded = ROWS_TO_LOAD else: self.rows_loaded = self.total_rows self.sig_setting_data.emit() self.set_size_and_type() self.reset()
python
def set_data(self, data, coll_filter=None): """Set model data""" self._data = data data_type = get_type_string(data) if coll_filter is not None and not self.remote and \ isinstance(data, (tuple, list, dict, set)): data = coll_filter(data) self.showndata = data self.header0 = _("Index") if self.names: self.header0 = _("Name") if isinstance(data, tuple): self.keys = list(range(len(data))) self.title += _("Tuple") elif isinstance(data, list): self.keys = list(range(len(data))) self.title += _("List") elif isinstance(data, set): self.keys = list(range(len(data))) self.title += _("Set") self._data = list(data) elif isinstance(data, dict): self.keys = list(data.keys()) self.title += _("Dictionary") if not self.names: self.header0 = _("Key") else: self.keys = get_object_attrs(data) self._data = data = self.showndata = ProxyObject(data) if not self.names: self.header0 = _("Attribute") if not isinstance(self._data, ProxyObject): self.title += (' (' + str(len(self.keys)) + ' ' + _("elements") + ')') else: self.title += data_type self.total_rows = len(self.keys) if self.total_rows > LARGE_NROWS: self.rows_loaded = ROWS_TO_LOAD else: self.rows_loaded = self.total_rows self.sig_setting_data.emit() self.set_size_and_type() self.reset()
[ "def", "set_data", "(", "self", ",", "data", ",", "coll_filter", "=", "None", ")", ":", "self", ".", "_data", "=", "data", "data_type", "=", "get_type_string", "(", "data", ")", "if", "coll_filter", "is", "not", "None", "and", "not", "self", ".", "remote", "and", "isinstance", "(", "data", ",", "(", "tuple", ",", "list", ",", "dict", ",", "set", ")", ")", ":", "data", "=", "coll_filter", "(", "data", ")", "self", ".", "showndata", "=", "data", "self", ".", "header0", "=", "_", "(", "\"Index\"", ")", "if", "self", ".", "names", ":", "self", ".", "header0", "=", "_", "(", "\"Name\"", ")", "if", "isinstance", "(", "data", ",", "tuple", ")", ":", "self", ".", "keys", "=", "list", "(", "range", "(", "len", "(", "data", ")", ")", ")", "self", ".", "title", "+=", "_", "(", "\"Tuple\"", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "self", ".", "keys", "=", "list", "(", "range", "(", "len", "(", "data", ")", ")", ")", "self", ".", "title", "+=", "_", "(", "\"List\"", ")", "elif", "isinstance", "(", "data", ",", "set", ")", ":", "self", ".", "keys", "=", "list", "(", "range", "(", "len", "(", "data", ")", ")", ")", "self", ".", "title", "+=", "_", "(", "\"Set\"", ")", "self", ".", "_data", "=", "list", "(", "data", ")", "elif", "isinstance", "(", "data", ",", "dict", ")", ":", "self", ".", "keys", "=", "list", "(", "data", ".", "keys", "(", ")", ")", "self", ".", "title", "+=", "_", "(", "\"Dictionary\"", ")", "if", "not", "self", ".", "names", ":", "self", ".", "header0", "=", "_", "(", "\"Key\"", ")", "else", ":", "self", ".", "keys", "=", "get_object_attrs", "(", "data", ")", "self", ".", "_data", "=", "data", "=", "self", ".", "showndata", "=", "ProxyObject", "(", "data", ")", "if", "not", "self", ".", "names", ":", "self", ".", "header0", "=", "_", "(", "\"Attribute\"", ")", "if", "not", "isinstance", "(", "self", ".", "_data", ",", "ProxyObject", ")", ":", "self", ".", "title", "+=", "(", "' ('", "+", "str", "(", "len", "(", "self", ".", "keys", ")", ")", "+", "' '", "+", "_", "(", "\"elements\"", ")", "+", "')'", ")", "else", ":", "self", ".", "title", "+=", "data_type", "self", ".", "total_rows", "=", "len", "(", "self", ".", "keys", ")", "if", "self", ".", "total_rows", ">", "LARGE_NROWS", ":", "self", ".", "rows_loaded", "=", "ROWS_TO_LOAD", "else", ":", "self", ".", "rows_loaded", "=", "self", ".", "total_rows", "self", ".", "sig_setting_data", ".", "emit", "(", ")", "self", ".", "set_size_and_type", "(", ")", "self", ".", "reset", "(", ")" ]
Set model data
[ "Set", "model", "data" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L147-L194
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.sort
def sort(self, column, order=Qt.AscendingOrder): """Overriding sort method""" reverse = (order==Qt.DescendingOrder) if column == 0: self.sizes = sort_against(self.sizes, self.keys, reverse) self.types = sort_against(self.types, self.keys, reverse) try: self.keys.sort(reverse=reverse) except: pass elif column == 1: self.keys[:self.rows_loaded] = sort_against(self.keys, self.types, reverse) self.sizes = sort_against(self.sizes, self.types, reverse) try: self.types.sort(reverse=reverse) except: pass elif column == 2: self.keys[:self.rows_loaded] = sort_against(self.keys, self.sizes, reverse) self.types = sort_against(self.types, self.sizes, reverse) try: self.sizes.sort(reverse=reverse) except: pass elif column == 3: values = [self._data[key] for key in self.keys] self.keys = sort_against(self.keys, values, reverse) self.sizes = sort_against(self.sizes, values, reverse) self.types = sort_against(self.types, values, reverse) self.beginResetModel() self.endResetModel()
python
def sort(self, column, order=Qt.AscendingOrder): """Overriding sort method""" reverse = (order==Qt.DescendingOrder) if column == 0: self.sizes = sort_against(self.sizes, self.keys, reverse) self.types = sort_against(self.types, self.keys, reverse) try: self.keys.sort(reverse=reverse) except: pass elif column == 1: self.keys[:self.rows_loaded] = sort_against(self.keys, self.types, reverse) self.sizes = sort_against(self.sizes, self.types, reverse) try: self.types.sort(reverse=reverse) except: pass elif column == 2: self.keys[:self.rows_loaded] = sort_against(self.keys, self.sizes, reverse) self.types = sort_against(self.types, self.sizes, reverse) try: self.sizes.sort(reverse=reverse) except: pass elif column == 3: values = [self._data[key] for key in self.keys] self.keys = sort_against(self.keys, values, reverse) self.sizes = sort_against(self.sizes, values, reverse) self.types = sort_against(self.types, values, reverse) self.beginResetModel() self.endResetModel()
[ "def", "sort", "(", "self", ",", "column", ",", "order", "=", "Qt", ".", "AscendingOrder", ")", ":", "reverse", "=", "(", "order", "==", "Qt", ".", "DescendingOrder", ")", "if", "column", "==", "0", ":", "self", ".", "sizes", "=", "sort_against", "(", "self", ".", "sizes", ",", "self", ".", "keys", ",", "reverse", ")", "self", ".", "types", "=", "sort_against", "(", "self", ".", "types", ",", "self", ".", "keys", ",", "reverse", ")", "try", ":", "self", ".", "keys", ".", "sort", "(", "reverse", "=", "reverse", ")", "except", ":", "pass", "elif", "column", "==", "1", ":", "self", ".", "keys", "[", ":", "self", ".", "rows_loaded", "]", "=", "sort_against", "(", "self", ".", "keys", ",", "self", ".", "types", ",", "reverse", ")", "self", ".", "sizes", "=", "sort_against", "(", "self", ".", "sizes", ",", "self", ".", "types", ",", "reverse", ")", "try", ":", "self", ".", "types", ".", "sort", "(", "reverse", "=", "reverse", ")", "except", ":", "pass", "elif", "column", "==", "2", ":", "self", ".", "keys", "[", ":", "self", ".", "rows_loaded", "]", "=", "sort_against", "(", "self", ".", "keys", ",", "self", ".", "sizes", ",", "reverse", ")", "self", ".", "types", "=", "sort_against", "(", "self", ".", "types", ",", "self", ".", "sizes", ",", "reverse", ")", "try", ":", "self", ".", "sizes", ".", "sort", "(", "reverse", "=", "reverse", ")", "except", ":", "pass", "elif", "column", "==", "3", ":", "values", "=", "[", "self", ".", "_data", "[", "key", "]", "for", "key", "in", "self", ".", "keys", "]", "self", ".", "keys", "=", "sort_against", "(", "self", ".", "keys", ",", "values", ",", "reverse", ")", "self", ".", "sizes", "=", "sort_against", "(", "self", ".", "sizes", ",", "values", ",", "reverse", ")", "self", ".", "types", "=", "sort_against", "(", "self", ".", "types", ",", "values", ",", "reverse", ")", "self", ".", "beginResetModel", "(", ")", "self", ".", "endResetModel", "(", ")" ]
Overriding sort method
[ "Overriding", "sort", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L230-L262
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.rowCount
def rowCount(self, index=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
python
def rowCount(self, index=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
[ "def", "rowCount", "(", "self", ",", "index", "=", "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/collectionseditor.py#L268-L273
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.get_value
def get_value(self, index): """Return current value""" if index.column() == 0: return self.keys[ index.row() ] elif index.column() == 1: return self.types[ index.row() ] elif index.column() == 2: return self.sizes[ index.row() ] else: return self._data[ self.keys[index.row()] ]
python
def get_value(self, index): """Return current value""" if index.column() == 0: return self.keys[ index.row() ] elif index.column() == 1: return self.types[ index.row() ] elif index.column() == 2: return self.sizes[ index.row() ] else: return self._data[ self.keys[index.row()] ]
[ "def", "get_value", "(", "self", ",", "index", ")", ":", "if", "index", ".", "column", "(", ")", "==", "0", ":", "return", "self", ".", "keys", "[", "index", ".", "row", "(", ")", "]", "elif", "index", ".", "column", "(", ")", "==", "1", ":", "return", "self", ".", "types", "[", "index", ".", "row", "(", ")", "]", "elif", "index", ".", "column", "(", ")", "==", "2", ":", "return", "self", ".", "sizes", "[", "index", ".", "row", "(", ")", "]", "else", ":", "return", "self", ".", "_data", "[", "self", ".", "keys", "[", "index", ".", "row", "(", ")", "]", "]" ]
Return current value
[ "Return", "current", "value" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L301-L310
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.get_bgcolor
def get_bgcolor(self, index): """Background color depending on value""" if index.column() == 0: color = QColor(Qt.lightGray) color.setAlphaF(.05) elif index.column() < 3: color = QColor(Qt.lightGray) color.setAlphaF(.2) else: color = QColor(Qt.lightGray) color.setAlphaF(.3) return color
python
def get_bgcolor(self, index): """Background color depending on value""" if index.column() == 0: color = QColor(Qt.lightGray) color.setAlphaF(.05) elif index.column() < 3: color = QColor(Qt.lightGray) color.setAlphaF(.2) else: color = QColor(Qt.lightGray) color.setAlphaF(.3) return color
[ "def", "get_bgcolor", "(", "self", ",", "index", ")", ":", "if", "index", ".", "column", "(", ")", "==", "0", ":", "color", "=", "QColor", "(", "Qt", ".", "lightGray", ")", "color", ".", "setAlphaF", "(", ".05", ")", "elif", "index", ".", "column", "(", ")", "<", "3", ":", "color", "=", "QColor", "(", "Qt", ".", "lightGray", ")", "color", ".", "setAlphaF", "(", ".2", ")", "else", ":", "color", "=", "QColor", "(", "Qt", ".", "lightGray", ")", "color", ".", "setAlphaF", "(", ".3", ")", "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/collectionseditor.py#L312-L323
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.data
def data(self, index, role=Qt.DisplayRole): """Cell content""" if not index.isValid(): return to_qvariant() value = self.get_value(index) if index.column() == 3 and self.remote: value = value['view'] if index.column() == 3: display = value_to_display(value, minmax=self.minmax) else: if is_type_text_string(value): display = to_text_string(value, encoding="utf-8") else: display = to_text_string(value) if role == Qt.DisplayRole: return to_qvariant(display) elif role == Qt.EditRole: return to_qvariant(value_to_display(value)) elif role == Qt.TextAlignmentRole: if index.column() == 3: if len(display.splitlines()) < 3: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) else: return to_qvariant(int(Qt.AlignLeft|Qt.AlignTop)) else: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) 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)) 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 index.column() == 3 and self.remote: value = value['view'] if index.column() == 3: display = value_to_display(value, minmax=self.minmax) else: if is_type_text_string(value): display = to_text_string(value, encoding="utf-8") else: display = to_text_string(value) if role == Qt.DisplayRole: return to_qvariant(display) elif role == Qt.EditRole: return to_qvariant(value_to_display(value)) elif role == Qt.TextAlignmentRole: if index.column() == 3: if len(display.splitlines()) < 3: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) else: return to_qvariant(int(Qt.AlignLeft|Qt.AlignTop)) else: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) 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)) return to_qvariant()
[ "def", "data", "(", "self", ",", "index", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "to_qvariant", "(", ")", "value", "=", "self", ".", "get_value", "(", "index", ")", "if", "index", ".", "column", "(", ")", "==", "3", "and", "self", ".", "remote", ":", "value", "=", "value", "[", "'view'", "]", "if", "index", ".", "column", "(", ")", "==", "3", ":", "display", "=", "value_to_display", "(", "value", ",", "minmax", "=", "self", ".", "minmax", ")", "else", ":", "if", "is_type_text_string", "(", "value", ")", ":", "display", "=", "to_text_string", "(", "value", ",", "encoding", "=", "\"utf-8\"", ")", "else", ":", "display", "=", "to_text_string", "(", "value", ")", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "return", "to_qvariant", "(", "display", ")", "elif", "role", "==", "Qt", ".", "EditRole", ":", "return", "to_qvariant", "(", "value_to_display", "(", "value", ")", ")", "elif", "role", "==", "Qt", ".", "TextAlignmentRole", ":", "if", "index", ".", "column", "(", ")", "==", "3", ":", "if", "len", "(", "display", ".", "splitlines", "(", ")", ")", "<", "3", ":", "return", "to_qvariant", "(", "int", "(", "Qt", ".", "AlignLeft", "|", "Qt", ".", "AlignVCenter", ")", ")", "else", ":", "return", "to_qvariant", "(", "int", "(", "Qt", ".", "AlignLeft", "|", "Qt", ".", "AlignTop", ")", ")", "else", ":", "return", "to_qvariant", "(", "int", "(", "Qt", ".", "AlignLeft", "|", "Qt", ".", "AlignVCenter", ")", ")", "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", ")", ")", "return", "to_qvariant", "(", ")" ]
Cell content
[ "Cell", "content" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L325-L355
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.headerData
def headerData(self, section, orientation, role=Qt.DisplayRole): """Overriding method headerData""" if role != Qt.DisplayRole: return to_qvariant() i_column = int(section) if orientation == Qt.Horizontal: headers = (self.header0, _("Type"), _("Size"), _("Value")) return to_qvariant( headers[i_column] ) else: return to_qvariant()
python
def headerData(self, section, orientation, role=Qt.DisplayRole): """Overriding method headerData""" if role != Qt.DisplayRole: return to_qvariant() i_column = int(section) if orientation == Qt.Horizontal: headers = (self.header0, _("Type"), _("Size"), _("Value")) return to_qvariant( headers[i_column] ) else: return to_qvariant()
[ "def", "headerData", "(", "self", ",", "section", ",", "orientation", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "role", "!=", "Qt", ".", "DisplayRole", ":", "return", "to_qvariant", "(", ")", "i_column", "=", "int", "(", "section", ")", "if", "orientation", "==", "Qt", ".", "Horizontal", ":", "headers", "=", "(", "self", ".", "header0", ",", "_", "(", "\"Type\"", ")", ",", "_", "(", "\"Size\"", ")", ",", "_", "(", "\"Value\"", ")", ")", "return", "to_qvariant", "(", "headers", "[", "i_column", "]", ")", "else", ":", "return", "to_qvariant", "(", ")" ]
Overriding method headerData
[ "Overriding", "method", "headerData" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L357-L366
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
ReadOnlyCollectionsModel.flags
def flags(self, index): """Overriding method flags""" # This method was implemented in CollectionsModel only, but to enable # tuple exploration (even without editing), this method was moved here if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable)
python
def flags(self, index): """Overriding method flags""" # This method was implemented in CollectionsModel only, but to enable # tuple exploration (even without editing), this method was moved here if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable)
[ "def", "flags", "(", "self", ",", "index", ")", ":", "# This method was implemented in CollectionsModel only, but to enable\r", "# tuple exploration (even without editing), this method was moved here\r", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "Qt", ".", "ItemIsEnabled", "return", "Qt", ".", "ItemFlags", "(", "QAbstractTableModel", ".", "flags", "(", "self", ",", "index", ")", "|", "Qt", ".", "ItemIsEditable", ")" ]
Overriding method flags
[ "Overriding", "method", "flags" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L368-L375
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsModel.set_value
def set_value(self, index, value): """Set value""" self._data[ self.keys[index.row()] ] = value self.showndata[ self.keys[index.row()] ] = value self.sizes[index.row()] = get_size(value) self.types[index.row()] = get_human_readable_type(value) self.sig_setting_data.emit()
python
def set_value(self, index, value): """Set value""" self._data[ self.keys[index.row()] ] = value self.showndata[ self.keys[index.row()] ] = value self.sizes[index.row()] = get_size(value) self.types[index.row()] = get_human_readable_type(value) self.sig_setting_data.emit()
[ "def", "set_value", "(", "self", ",", "index", ",", "value", ")", ":", "self", ".", "_data", "[", "self", ".", "keys", "[", "index", ".", "row", "(", ")", "]", "]", "=", "value", "self", ".", "showndata", "[", "self", ".", "keys", "[", "index", ".", "row", "(", ")", "]", "]", "=", "value", "self", ".", "sizes", "[", "index", ".", "row", "(", ")", "]", "=", "get_size", "(", "value", ")", "self", ".", "types", "[", "index", ".", "row", "(", ")", "]", "=", "get_human_readable_type", "(", "value", ")", "self", ".", "sig_setting_data", ".", "emit", "(", ")" ]
Set value
[ "Set", "value" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L384-L390
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsModel.get_bgcolor
def get_bgcolor(self, index): """Background color depending on value""" value = self.get_value(index) if index.column() < 3: color = ReadOnlyCollectionsModel.get_bgcolor(self, index) else: if self.remote: color_name = value['color'] else: color_name = get_color_name(value) color = QColor(color_name) color.setAlphaF(.2) return color
python
def get_bgcolor(self, index): """Background color depending on value""" value = self.get_value(index) if index.column() < 3: color = ReadOnlyCollectionsModel.get_bgcolor(self, index) else: if self.remote: color_name = value['color'] else: color_name = get_color_name(value) color = QColor(color_name) color.setAlphaF(.2) return color
[ "def", "get_bgcolor", "(", "self", ",", "index", ")", ":", "value", "=", "self", ".", "get_value", "(", "index", ")", "if", "index", ".", "column", "(", ")", "<", "3", ":", "color", "=", "ReadOnlyCollectionsModel", ".", "get_bgcolor", "(", "self", ",", "index", ")", "else", ":", "if", "self", ".", "remote", ":", "color_name", "=", "value", "[", "'color'", "]", "else", ":", "color_name", "=", "get_color_name", "(", "value", ")", "color", "=", "QColor", "(", "color_name", ")", "color", ".", "setAlphaF", "(", ".2", ")", "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/collectionseditor.py#L392-L404
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsModel.setData
def setData(self, index, value, role=Qt.EditRole): """Cell content change""" if not index.isValid(): return False if index.column() < 3: return False value = display_to_value(value, self.get_value(index), ignore_errors=True) self.set_value(index, value) self.dataChanged.emit(index, index) return True
python
def setData(self, index, value, role=Qt.EditRole): """Cell content change""" if not index.isValid(): return False if index.column() < 3: return False value = display_to_value(value, self.get_value(index), ignore_errors=True) self.set_value(index, value) self.dataChanged.emit(index, index) return True
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "False", "if", "index", ".", "column", "(", ")", "<", "3", ":", "return", "False", "value", "=", "display_to_value", "(", "value", ",", "self", ".", "get_value", "(", "index", ")", ",", "ignore_errors", "=", "True", ")", "self", ".", "set_value", "(", "index", ",", "value", ")", "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/collectionseditor.py#L406-L416
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsDelegate.show_warning
def show_warning(self, index): """ Decide if showing a warning when the user is trying to view a big variable associated to a Tablemodel index This avoids getting the variables' value to know its size and type, using instead those already computed by the TableModel. The problem is when a variable is too big, it can take a lot of time just to get its value """ try: val_size = index.model().sizes[index.row()] val_type = index.model().types[index.row()] except: return False if val_type in ['list', 'set', 'tuple', 'dict'] and \ int(val_size) > 1e5: return True else: return False
python
def show_warning(self, index): """ Decide if showing a warning when the user is trying to view a big variable associated to a Tablemodel index This avoids getting the variables' value to know its size and type, using instead those already computed by the TableModel. The problem is when a variable is too big, it can take a lot of time just to get its value """ try: val_size = index.model().sizes[index.row()] val_type = index.model().types[index.row()] except: return False if val_type in ['list', 'set', 'tuple', 'dict'] and \ int(val_size) > 1e5: return True else: return False
[ "def", "show_warning", "(", "self", ",", "index", ")", ":", "try", ":", "val_size", "=", "index", ".", "model", "(", ")", ".", "sizes", "[", "index", ".", "row", "(", ")", "]", "val_type", "=", "index", ".", "model", "(", ")", ".", "types", "[", "index", ".", "row", "(", ")", "]", "except", ":", "return", "False", "if", "val_type", "in", "[", "'list'", ",", "'set'", ",", "'tuple'", ",", "'dict'", "]", "and", "int", "(", "val_size", ")", ">", "1e5", ":", "return", "True", "else", ":", "return", "False" ]
Decide if showing a warning when the user is trying to view a big variable associated to a Tablemodel index This avoids getting the variables' value to know its size and type, using instead those already computed by the TableModel. The problem is when a variable is too big, it can take a lot of time just to get its value
[ "Decide", "if", "showing", "a", "warning", "when", "the", "user", "is", "trying", "to", "view", "a", "big", "variable", "associated", "to", "a", "Tablemodel", "index", "This", "avoids", "getting", "the", "variables", "value", "to", "know", "its", "size", "and", "type", "using", "instead", "those", "already", "computed", "by", "the", "TableModel", ".", "The", "problem", "is", "when", "a", "variable", "is", "too", "big", "it", "can", "take", "a", "lot", "of", "time", "just", "to", "get", "its", "value" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L435-L456
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsDelegate.createEditor
def createEditor(self, parent, option, index): """Overriding method createEditor""" if index.column() < 3: return None if self.show_warning(index): answer = QMessageBox.warning(self.parent(), _("Warning"), _("Opening this variable can be slow\n\n" "Do you want to continue anyway?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: return None try: value = self.get_value(index) if value is None: return None except Exception as msg: QMessageBox.critical(self.parent(), _("Error"), _("Spyder was unable to retrieve the value of " "this variable from the console.<br><br>" "The error mesage was:<br>" "<i>%s</i>" ) % to_text_string(msg)) return key = index.model().get_key(index) readonly = (isinstance(value, (tuple, set)) or self.parent().readonly or not is_known_type(value)) # CollectionsEditor for a list, tuple, dict, etc. if isinstance(value, (list, set, tuple, dict)): editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for a Numpy array elif isinstance(value, (ndarray, MaskedArray)) \ and ndarray is not FakeObject: editor = ArrayEditor(parent=parent) if not editor.setup_and_check(value, title=key, readonly=readonly): return self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for an images elif isinstance(value, Image) and ndarray is not FakeObject \ and Image is not FakeObject: arr = array(value) editor = ArrayEditor(parent=parent) if not editor.setup_and_check(arr, title=key, readonly=readonly): return conv_func = lambda arr: Image.fromarray(arr, mode=value.mode) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly, conv=conv_func)) return None # DataFrameEditor for a pandas dataframe, series or index elif isinstance(value, (DataFrame, Index, Series)) \ and DataFrame is not FakeObject: editor = DataFrameEditor(parent=parent) if not editor.setup_and_check(value, title=key): return editor.dataModel.set_format(index.model().dataframe_format) editor.sig_option_changed.connect(self.change_option) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QDateEdit and QDateTimeEdit for a dates or datetime respectively elif isinstance(value, datetime.date): if readonly: return None else: if isinstance(value, datetime.datetime): editor = QDateTimeEdit(value, parent=parent) else: editor = QDateEdit(value, parent=parent) editor.setCalendarPopup(True) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return editor # TextEditor for a long string elif is_text_string(value) and len(value) > 40: te = TextEditor(None, parent=parent) if te.setup_and_check(value): editor = TextEditor(value, key, readonly=readonly, parent=parent) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QLineEdit for an individual value (int, float, short string, etc) elif is_editable_type(value): if readonly: return None else: editor = QLineEdit(parent=parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignLeft) # This is making Spyder crash because the QLineEdit that it's # been modified is removed and a new one is created after # evaluation. So the object on which this method is trying to # act doesn't exist anymore. # editor.returnPressed.connect(self.commitAndCloseEditor) return editor # CollectionsEditor for an arbitrary Python object else: editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None
python
def createEditor(self, parent, option, index): """Overriding method createEditor""" if index.column() < 3: return None if self.show_warning(index): answer = QMessageBox.warning(self.parent(), _("Warning"), _("Opening this variable can be slow\n\n" "Do you want to continue anyway?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: return None try: value = self.get_value(index) if value is None: return None except Exception as msg: QMessageBox.critical(self.parent(), _("Error"), _("Spyder was unable to retrieve the value of " "this variable from the console.<br><br>" "The error mesage was:<br>" "<i>%s</i>" ) % to_text_string(msg)) return key = index.model().get_key(index) readonly = (isinstance(value, (tuple, set)) or self.parent().readonly or not is_known_type(value)) # CollectionsEditor for a list, tuple, dict, etc. if isinstance(value, (list, set, tuple, dict)): editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for a Numpy array elif isinstance(value, (ndarray, MaskedArray)) \ and ndarray is not FakeObject: editor = ArrayEditor(parent=parent) if not editor.setup_and_check(value, title=key, readonly=readonly): return self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for an images elif isinstance(value, Image) and ndarray is not FakeObject \ and Image is not FakeObject: arr = array(value) editor = ArrayEditor(parent=parent) if not editor.setup_and_check(arr, title=key, readonly=readonly): return conv_func = lambda arr: Image.fromarray(arr, mode=value.mode) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly, conv=conv_func)) return None # DataFrameEditor for a pandas dataframe, series or index elif isinstance(value, (DataFrame, Index, Series)) \ and DataFrame is not FakeObject: editor = DataFrameEditor(parent=parent) if not editor.setup_and_check(value, title=key): return editor.dataModel.set_format(index.model().dataframe_format) editor.sig_option_changed.connect(self.change_option) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QDateEdit and QDateTimeEdit for a dates or datetime respectively elif isinstance(value, datetime.date): if readonly: return None else: if isinstance(value, datetime.datetime): editor = QDateTimeEdit(value, parent=parent) else: editor = QDateEdit(value, parent=parent) editor.setCalendarPopup(True) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return editor # TextEditor for a long string elif is_text_string(value) and len(value) > 40: te = TextEditor(None, parent=parent) if te.setup_and_check(value): editor = TextEditor(value, key, readonly=readonly, parent=parent) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QLineEdit for an individual value (int, float, short string, etc) elif is_editable_type(value): if readonly: return None else: editor = QLineEdit(parent=parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignLeft) # This is making Spyder crash because the QLineEdit that it's # been modified is removed and a new one is created after # evaluation. So the object on which this method is trying to # act doesn't exist anymore. # editor.returnPressed.connect(self.commitAndCloseEditor) return editor # CollectionsEditor for an arbitrary Python object else: editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None
[ "def", "createEditor", "(", "self", ",", "parent", ",", "option", ",", "index", ")", ":", "if", "index", ".", "column", "(", ")", "<", "3", ":", "return", "None", "if", "self", ".", "show_warning", "(", "index", ")", ":", "answer", "=", "QMessageBox", ".", "warning", "(", "self", ".", "parent", "(", ")", ",", "_", "(", "\"Warning\"", ")", ",", "_", "(", "\"Opening this variable can be slow\\n\\n\"", "\"Do you want to continue anyway?\"", ")", ",", "QMessageBox", ".", "Yes", "|", "QMessageBox", ".", "No", ")", "if", "answer", "==", "QMessageBox", ".", "No", ":", "return", "None", "try", ":", "value", "=", "self", ".", "get_value", "(", "index", ")", "if", "value", "is", "None", ":", "return", "None", "except", "Exception", "as", "msg", ":", "QMessageBox", ".", "critical", "(", "self", ".", "parent", "(", ")", ",", "_", "(", "\"Error\"", ")", ",", "_", "(", "\"Spyder was unable to retrieve the value of \"", "\"this variable from the console.<br><br>\"", "\"The error mesage was:<br>\"", "\"<i>%s</i>\"", ")", "%", "to_text_string", "(", "msg", ")", ")", "return", "key", "=", "index", ".", "model", "(", ")", ".", "get_key", "(", "index", ")", "readonly", "=", "(", "isinstance", "(", "value", ",", "(", "tuple", ",", "set", ")", ")", "or", "self", ".", "parent", "(", ")", ".", "readonly", "or", "not", "is_known_type", "(", "value", ")", ")", "# CollectionsEditor for a list, tuple, dict, etc.\r", "if", "isinstance", "(", "value", ",", "(", "list", ",", "set", ",", "tuple", ",", "dict", ")", ")", ":", "editor", "=", "CollectionsEditor", "(", "parent", "=", "parent", ")", "editor", ".", "setup", "(", "value", ",", "key", ",", "icon", "=", "self", ".", "parent", "(", ")", ".", "windowIcon", "(", ")", ",", "readonly", "=", "readonly", ")", "self", ".", "create_dialog", "(", "editor", ",", "dict", "(", "model", "=", "index", ".", "model", "(", ")", ",", "editor", "=", "editor", ",", "key", "=", "key", ",", "readonly", "=", "readonly", ")", ")", "return", "None", "# ArrayEditor for a Numpy array\r", "elif", "isinstance", "(", "value", ",", "(", "ndarray", ",", "MaskedArray", ")", ")", "and", "ndarray", "is", "not", "FakeObject", ":", "editor", "=", "ArrayEditor", "(", "parent", "=", "parent", ")", "if", "not", "editor", ".", "setup_and_check", "(", "value", ",", "title", "=", "key", ",", "readonly", "=", "readonly", ")", ":", "return", "self", ".", "create_dialog", "(", "editor", ",", "dict", "(", "model", "=", "index", ".", "model", "(", ")", ",", "editor", "=", "editor", ",", "key", "=", "key", ",", "readonly", "=", "readonly", ")", ")", "return", "None", "# ArrayEditor for an images\r", "elif", "isinstance", "(", "value", ",", "Image", ")", "and", "ndarray", "is", "not", "FakeObject", "and", "Image", "is", "not", "FakeObject", ":", "arr", "=", "array", "(", "value", ")", "editor", "=", "ArrayEditor", "(", "parent", "=", "parent", ")", "if", "not", "editor", ".", "setup_and_check", "(", "arr", ",", "title", "=", "key", ",", "readonly", "=", "readonly", ")", ":", "return", "conv_func", "=", "lambda", "arr", ":", "Image", ".", "fromarray", "(", "arr", ",", "mode", "=", "value", ".", "mode", ")", "self", ".", "create_dialog", "(", "editor", ",", "dict", "(", "model", "=", "index", ".", "model", "(", ")", ",", "editor", "=", "editor", ",", "key", "=", "key", ",", "readonly", "=", "readonly", ",", "conv", "=", "conv_func", ")", ")", "return", "None", "# DataFrameEditor for a pandas dataframe, series or index\r", "elif", "isinstance", "(", "value", ",", "(", "DataFrame", ",", "Index", ",", "Series", ")", ")", "and", "DataFrame", "is", "not", "FakeObject", ":", "editor", "=", "DataFrameEditor", "(", "parent", "=", "parent", ")", "if", "not", "editor", ".", "setup_and_check", "(", "value", ",", "title", "=", "key", ")", ":", "return", "editor", ".", "dataModel", ".", "set_format", "(", "index", ".", "model", "(", ")", ".", "dataframe_format", ")", "editor", ".", "sig_option_changed", ".", "connect", "(", "self", ".", "change_option", ")", "self", ".", "create_dialog", "(", "editor", ",", "dict", "(", "model", "=", "index", ".", "model", "(", ")", ",", "editor", "=", "editor", ",", "key", "=", "key", ",", "readonly", "=", "readonly", ")", ")", "return", "None", "# QDateEdit and QDateTimeEdit for a dates or datetime respectively\r", "elif", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "if", "readonly", ":", "return", "None", "else", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "editor", "=", "QDateTimeEdit", "(", "value", ",", "parent", "=", "parent", ")", "else", ":", "editor", "=", "QDateEdit", "(", "value", ",", "parent", "=", "parent", ")", "editor", ".", "setCalendarPopup", "(", "True", ")", "editor", ".", "setFont", "(", "get_font", "(", "font_size_delta", "=", "DEFAULT_SMALL_DELTA", ")", ")", "return", "editor", "# TextEditor for a long string\r", "elif", "is_text_string", "(", "value", ")", "and", "len", "(", "value", ")", ">", "40", ":", "te", "=", "TextEditor", "(", "None", ",", "parent", "=", "parent", ")", "if", "te", ".", "setup_and_check", "(", "value", ")", ":", "editor", "=", "TextEditor", "(", "value", ",", "key", ",", "readonly", "=", "readonly", ",", "parent", "=", "parent", ")", "self", ".", "create_dialog", "(", "editor", ",", "dict", "(", "model", "=", "index", ".", "model", "(", ")", ",", "editor", "=", "editor", ",", "key", "=", "key", ",", "readonly", "=", "readonly", ")", ")", "return", "None", "# QLineEdit for an individual value (int, float, short string, etc)\r", "elif", "is_editable_type", "(", "value", ")", ":", "if", "readonly", ":", "return", "None", "else", ":", "editor", "=", "QLineEdit", "(", "parent", "=", "parent", ")", "editor", ".", "setFont", "(", "get_font", "(", "font_size_delta", "=", "DEFAULT_SMALL_DELTA", ")", ")", "editor", ".", "setAlignment", "(", "Qt", ".", "AlignLeft", ")", "# This is making Spyder crash because the QLineEdit that it's\r", "# been modified is removed and a new one is created after\r", "# evaluation. So the object on which this method is trying to\r", "# act doesn't exist anymore.\r", "# editor.returnPressed.connect(self.commitAndCloseEditor)\r", "return", "editor", "# CollectionsEditor for an arbitrary Python object\r", "else", ":", "editor", "=", "CollectionsEditor", "(", "parent", "=", "parent", ")", "editor", ".", "setup", "(", "value", ",", "key", ",", "icon", "=", "self", ".", "parent", "(", ")", ".", "windowIcon", "(", ")", ",", "readonly", "=", "readonly", ")", "self", ".", "create_dialog", "(", "editor", ",", "dict", "(", "model", "=", "index", ".", "model", "(", ")", ",", "editor", "=", "editor", ",", "key", "=", "key", ",", "readonly", "=", "readonly", ")", ")", "return", "None" ]
Overriding method createEditor
[ "Overriding", "method", "createEditor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L458-L567
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsDelegate.setEditorData
def setEditorData(self, editor, index): """ Overriding method setEditorData Model --> Editor """ value = self.get_value(index) if isinstance(editor, QLineEdit): if is_binary_string(value): try: value = to_text_string(value, 'utf8') except: pass if not is_text_string(value): value = repr(value) editor.setText(value) elif isinstance(editor, QDateEdit): editor.setDate(value) elif isinstance(editor, QDateTimeEdit): editor.setDateTime(QDateTime(value.date(), value.time()))
python
def setEditorData(self, editor, index): """ Overriding method setEditorData Model --> Editor """ value = self.get_value(index) if isinstance(editor, QLineEdit): if is_binary_string(value): try: value = to_text_string(value, 'utf8') except: pass if not is_text_string(value): value = repr(value) editor.setText(value) elif isinstance(editor, QDateEdit): editor.setDate(value) elif isinstance(editor, QDateTimeEdit): editor.setDateTime(QDateTime(value.date(), value.time()))
[ "def", "setEditorData", "(", "self", ",", "editor", ",", "index", ")", ":", "value", "=", "self", ".", "get_value", "(", "index", ")", "if", "isinstance", "(", "editor", ",", "QLineEdit", ")", ":", "if", "is_binary_string", "(", "value", ")", ":", "try", ":", "value", "=", "to_text_string", "(", "value", ",", "'utf8'", ")", "except", ":", "pass", "if", "not", "is_text_string", "(", "value", ")", ":", "value", "=", "repr", "(", "value", ")", "editor", ".", "setText", "(", "value", ")", "elif", "isinstance", "(", "editor", ",", "QDateEdit", ")", ":", "editor", ".", "setDate", "(", "value", ")", "elif", "isinstance", "(", "editor", ",", "QDateTimeEdit", ")", ":", "editor", ".", "setDateTime", "(", "QDateTime", "(", "value", ".", "date", "(", ")", ",", "value", ".", "time", "(", ")", ")", ")" ]
Overriding method setEditorData Model --> Editor
[ "Overriding", "method", "setEditorData", "Model", "--", ">", "Editor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L630-L648
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsDelegate.setModelData
def setModelData(self, editor, model, index): """ Overriding method setModelData Editor --> Model """ if not hasattr(model, "set_value"): # Read-only mode return if isinstance(editor, QLineEdit): value = editor.text() try: value = display_to_value(to_qvariant(value), self.get_value(index), ignore_errors=False) except Exception as msg: raise QMessageBox.critical(editor, _("Edit item"), _("<b>Unable to assign data to item.</b>" "<br><br>Error message:<br>%s" ) % str(msg)) return elif isinstance(editor, QDateEdit): qdate = editor.date() value = datetime.date( qdate.year(), qdate.month(), qdate.day() ) elif isinstance(editor, QDateTimeEdit): qdatetime = editor.dateTime() qdate = qdatetime.date() qtime = qdatetime.time() value = datetime.datetime( qdate.year(), qdate.month(), qdate.day(), qtime.hour(), qtime.minute(), qtime.second() ) else: # Should not happen... raise RuntimeError("Unsupported editor widget") self.set_value(index, value)
python
def setModelData(self, editor, model, index): """ Overriding method setModelData Editor --> Model """ if not hasattr(model, "set_value"): # Read-only mode return if isinstance(editor, QLineEdit): value = editor.text() try: value = display_to_value(to_qvariant(value), self.get_value(index), ignore_errors=False) except Exception as msg: raise QMessageBox.critical(editor, _("Edit item"), _("<b>Unable to assign data to item.</b>" "<br><br>Error message:<br>%s" ) % str(msg)) return elif isinstance(editor, QDateEdit): qdate = editor.date() value = datetime.date( qdate.year(), qdate.month(), qdate.day() ) elif isinstance(editor, QDateTimeEdit): qdatetime = editor.dateTime() qdate = qdatetime.date() qtime = qdatetime.time() value = datetime.datetime( qdate.year(), qdate.month(), qdate.day(), qtime.hour(), qtime.minute(), qtime.second() ) else: # Should not happen... raise RuntimeError("Unsupported editor widget") self.set_value(index, value)
[ "def", "setModelData", "(", "self", ",", "editor", ",", "model", ",", "index", ")", ":", "if", "not", "hasattr", "(", "model", ",", "\"set_value\"", ")", ":", "# Read-only mode\r", "return", "if", "isinstance", "(", "editor", ",", "QLineEdit", ")", ":", "value", "=", "editor", ".", "text", "(", ")", "try", ":", "value", "=", "display_to_value", "(", "to_qvariant", "(", "value", ")", ",", "self", ".", "get_value", "(", "index", ")", ",", "ignore_errors", "=", "False", ")", "except", "Exception", "as", "msg", ":", "raise", "QMessageBox", ".", "critical", "(", "editor", ",", "_", "(", "\"Edit item\"", ")", ",", "_", "(", "\"<b>Unable to assign data to item.</b>\"", "\"<br><br>Error message:<br>%s\"", ")", "%", "str", "(", "msg", ")", ")", "return", "elif", "isinstance", "(", "editor", ",", "QDateEdit", ")", ":", "qdate", "=", "editor", ".", "date", "(", ")", "value", "=", "datetime", ".", "date", "(", "qdate", ".", "year", "(", ")", ",", "qdate", ".", "month", "(", ")", ",", "qdate", ".", "day", "(", ")", ")", "elif", "isinstance", "(", "editor", ",", "QDateTimeEdit", ")", ":", "qdatetime", "=", "editor", ".", "dateTime", "(", ")", "qdate", "=", "qdatetime", ".", "date", "(", ")", "qtime", "=", "qdatetime", ".", "time", "(", ")", "value", "=", "datetime", ".", "datetime", "(", "qdate", ".", "year", "(", ")", ",", "qdate", ".", "month", "(", ")", ",", "qdate", ".", "day", "(", ")", ",", "qtime", ".", "hour", "(", ")", ",", "qtime", ".", "minute", "(", ")", ",", "qtime", ".", "second", "(", ")", ")", "else", ":", "# Should not happen...\r", "raise", "RuntimeError", "(", "\"Unsupported editor widget\"", ")", "self", ".", "set_value", "(", "index", ",", "value", ")" ]
Overriding method setModelData Editor --> Model
[ "Overriding", "method", "setModelData", "Editor", "--", ">", "Model" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L650-L685
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.setup_table
def setup_table(self): """Setup table""" self.horizontalHeader().setStretchLastSection(True) self.adjust_columns() # Sorting columns self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder)
python
def setup_table(self): """Setup table""" self.horizontalHeader().setStretchLastSection(True) self.adjust_columns() # Sorting columns self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder)
[ "def", "setup_table", "(", "self", ")", ":", "self", ".", "horizontalHeader", "(", ")", ".", "setStretchLastSection", "(", "True", ")", "self", ".", "adjust_columns", "(", ")", "# Sorting columns\r", "self", ".", "setSortingEnabled", "(", "True", ")", "self", ".", "sortByColumn", "(", "0", ",", "Qt", ".", "AscendingOrder", ")" ]
Setup table
[ "Setup", "table" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L745-L751
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.setup_menu
def setup_menu(self, minmax): """Setup context menu""" if self.minmax_action is not None: self.minmax_action.setChecked(minmax) return resize_action = create_action(self, _("Resize rows to contents"), triggered=self.resizeRowsToContents) resize_columns_action = create_action( self, _("Resize columns to contents"), triggered=self.resize_column_contents) self.paste_action = create_action(self, _("Paste"), icon=ima.icon('editpaste'), triggered=self.paste) self.copy_action = create_action(self, _("Copy"), icon=ima.icon('editcopy'), triggered=self.copy) self.edit_action = create_action(self, _("Edit"), icon=ima.icon('edit'), triggered=self.edit_item) self.plot_action = create_action(self, _("Plot"), icon=ima.icon('plot'), triggered=lambda: self.plot_item('plot')) self.plot_action.setVisible(False) self.hist_action = create_action(self, _("Histogram"), icon=ima.icon('hist'), triggered=lambda: self.plot_item('hist')) self.hist_action.setVisible(False) self.imshow_action = create_action(self, _("Show image"), icon=ima.icon('imshow'), triggered=self.imshow_item) self.imshow_action.setVisible(False) self.save_array_action = create_action(self, _("Save array"), icon=ima.icon('filesave'), triggered=self.save_array) self.save_array_action.setVisible(False) self.insert_action = create_action(self, _("Insert"), icon=ima.icon('insert'), triggered=self.insert_item) self.remove_action = create_action(self, _("Remove"), icon=ima.icon('editdelete'), triggered=self.remove_item) self.minmax_action = create_action(self, _("Show arrays min/max"), toggled=self.toggle_minmax) self.minmax_action.setChecked(minmax) self.toggle_minmax(minmax) self.rename_action = create_action(self, _("Rename"), icon=ima.icon('rename'), triggered=self.rename_item) self.duplicate_action = create_action(self, _("Duplicate"), icon=ima.icon('edit_add'), triggered=self.duplicate_item) menu = QMenu(self) menu_actions = [self.edit_action, self.plot_action, self.hist_action, self.imshow_action, self.save_array_action, self.insert_action, self.remove_action, self.copy_action, self.paste_action, None, self.rename_action, self.duplicate_action, None, resize_action, resize_columns_action] if ndarray is not FakeObject: menu_actions.append(self.minmax_action) add_actions(menu, menu_actions) self.empty_ws_menu = QMenu(self) add_actions(self.empty_ws_menu, [self.insert_action, self.paste_action, None, resize_action, resize_columns_action]) return menu
python
def setup_menu(self, minmax): """Setup context menu""" if self.minmax_action is not None: self.minmax_action.setChecked(minmax) return resize_action = create_action(self, _("Resize rows to contents"), triggered=self.resizeRowsToContents) resize_columns_action = create_action( self, _("Resize columns to contents"), triggered=self.resize_column_contents) self.paste_action = create_action(self, _("Paste"), icon=ima.icon('editpaste'), triggered=self.paste) self.copy_action = create_action(self, _("Copy"), icon=ima.icon('editcopy'), triggered=self.copy) self.edit_action = create_action(self, _("Edit"), icon=ima.icon('edit'), triggered=self.edit_item) self.plot_action = create_action(self, _("Plot"), icon=ima.icon('plot'), triggered=lambda: self.plot_item('plot')) self.plot_action.setVisible(False) self.hist_action = create_action(self, _("Histogram"), icon=ima.icon('hist'), triggered=lambda: self.plot_item('hist')) self.hist_action.setVisible(False) self.imshow_action = create_action(self, _("Show image"), icon=ima.icon('imshow'), triggered=self.imshow_item) self.imshow_action.setVisible(False) self.save_array_action = create_action(self, _("Save array"), icon=ima.icon('filesave'), triggered=self.save_array) self.save_array_action.setVisible(False) self.insert_action = create_action(self, _("Insert"), icon=ima.icon('insert'), triggered=self.insert_item) self.remove_action = create_action(self, _("Remove"), icon=ima.icon('editdelete'), triggered=self.remove_item) self.minmax_action = create_action(self, _("Show arrays min/max"), toggled=self.toggle_minmax) self.minmax_action.setChecked(minmax) self.toggle_minmax(minmax) self.rename_action = create_action(self, _("Rename"), icon=ima.icon('rename'), triggered=self.rename_item) self.duplicate_action = create_action(self, _("Duplicate"), icon=ima.icon('edit_add'), triggered=self.duplicate_item) menu = QMenu(self) menu_actions = [self.edit_action, self.plot_action, self.hist_action, self.imshow_action, self.save_array_action, self.insert_action, self.remove_action, self.copy_action, self.paste_action, None, self.rename_action, self.duplicate_action, None, resize_action, resize_columns_action] if ndarray is not FakeObject: menu_actions.append(self.minmax_action) add_actions(menu, menu_actions) self.empty_ws_menu = QMenu(self) add_actions(self.empty_ws_menu, [self.insert_action, self.paste_action, None, resize_action, resize_columns_action]) return menu
[ "def", "setup_menu", "(", "self", ",", "minmax", ")", ":", "if", "self", ".", "minmax_action", "is", "not", "None", ":", "self", ".", "minmax_action", ".", "setChecked", "(", "minmax", ")", "return", "resize_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Resize rows to contents\"", ")", ",", "triggered", "=", "self", ".", "resizeRowsToContents", ")", "resize_columns_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Resize columns to contents\"", ")", ",", "triggered", "=", "self", ".", "resize_column_contents", ")", "self", ".", "paste_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Paste\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'editpaste'", ")", ",", "triggered", "=", "self", ".", "paste", ")", "self", ".", "copy_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Copy\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'editcopy'", ")", ",", "triggered", "=", "self", ".", "copy", ")", "self", ".", "edit_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Edit\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'edit'", ")", ",", "triggered", "=", "self", ".", "edit_item", ")", "self", ".", "plot_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Plot\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'plot'", ")", ",", "triggered", "=", "lambda", ":", "self", ".", "plot_item", "(", "'plot'", ")", ")", "self", ".", "plot_action", ".", "setVisible", "(", "False", ")", "self", ".", "hist_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Histogram\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'hist'", ")", ",", "triggered", "=", "lambda", ":", "self", ".", "plot_item", "(", "'hist'", ")", ")", "self", ".", "hist_action", ".", "setVisible", "(", "False", ")", "self", ".", "imshow_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Show image\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'imshow'", ")", ",", "triggered", "=", "self", ".", "imshow_item", ")", "self", ".", "imshow_action", ".", "setVisible", "(", "False", ")", "self", ".", "save_array_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Save array\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'filesave'", ")", ",", "triggered", "=", "self", ".", "save_array", ")", "self", ".", "save_array_action", ".", "setVisible", "(", "False", ")", "self", ".", "insert_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Insert\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'insert'", ")", ",", "triggered", "=", "self", ".", "insert_item", ")", "self", ".", "remove_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Remove\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'editdelete'", ")", ",", "triggered", "=", "self", ".", "remove_item", ")", "self", ".", "minmax_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Show arrays min/max\"", ")", ",", "toggled", "=", "self", ".", "toggle_minmax", ")", "self", ".", "minmax_action", ".", "setChecked", "(", "minmax", ")", "self", ".", "toggle_minmax", "(", "minmax", ")", "self", ".", "rename_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Rename\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'rename'", ")", ",", "triggered", "=", "self", ".", "rename_item", ")", "self", ".", "duplicate_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Duplicate\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'edit_add'", ")", ",", "triggered", "=", "self", ".", "duplicate_item", ")", "menu", "=", "QMenu", "(", "self", ")", "menu_actions", "=", "[", "self", ".", "edit_action", ",", "self", ".", "plot_action", ",", "self", ".", "hist_action", ",", "self", ".", "imshow_action", ",", "self", ".", "save_array_action", ",", "self", ".", "insert_action", ",", "self", ".", "remove_action", ",", "self", ".", "copy_action", ",", "self", ".", "paste_action", ",", "None", ",", "self", ".", "rename_action", ",", "self", ".", "duplicate_action", ",", "None", ",", "resize_action", ",", "resize_columns_action", "]", "if", "ndarray", "is", "not", "FakeObject", ":", "menu_actions", ".", "append", "(", "self", ".", "minmax_action", ")", "add_actions", "(", "menu", ",", "menu_actions", ")", "self", ".", "empty_ws_menu", "=", "QMenu", "(", "self", ")", "add_actions", "(", "self", ".", "empty_ws_menu", ",", "[", "self", ".", "insert_action", ",", "self", ".", "paste_action", ",", "None", ",", "resize_action", ",", "resize_columns_action", "]", ")", "return", "menu" ]
Setup context menu
[ "Setup", "context", "menu" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L753-L820
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.refresh_menu
def refresh_menu(self): """Refresh context menu""" index = self.currentIndex() condition = index.isValid() self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.refresh_plot_entries(index)
python
def refresh_menu(self): """Refresh context menu""" index = self.currentIndex() condition = index.isValid() self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.refresh_plot_entries(index)
[ "def", "refresh_menu", "(", "self", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "condition", "=", "index", ".", "isValid", "(", ")", "self", ".", "edit_action", ".", "setEnabled", "(", "condition", ")", "self", ".", "remove_action", ".", "setEnabled", "(", "condition", ")", "self", ".", "refresh_plot_entries", "(", "index", ")" ]
Refresh context menu
[ "Refresh", "context", "menu" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L880-L886
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.set_data
def set_data(self, data): """Set table data""" if data is not None: self.model.set_data(data, self.dictfilter) self.sortByColumn(0, Qt.AscendingOrder)
python
def set_data(self, data): """Set table data""" if data is not None: self.model.set_data(data, self.dictfilter) self.sortByColumn(0, Qt.AscendingOrder)
[ "def", "set_data", "(", "self", ",", "data", ")", ":", "if", "data", "is", "not", "None", ":", "self", ".", "model", ".", "set_data", "(", "data", ",", "self", ".", "dictfilter", ")", "self", ".", "sortByColumn", "(", "0", ",", "Qt", ".", "AscendingOrder", ")" ]
Set table data
[ "Set", "table", "data" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L920-L924
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.mousePressEvent
def mousePressEvent(self, event): """Reimplement Qt method""" if event.button() != Qt.LeftButton: QTableView.mousePressEvent(self, event) return index_clicked = self.indexAt(event.pos()) if index_clicked.isValid(): if index_clicked == self.currentIndex() \ and index_clicked in self.selectedIndexes(): self.clearSelection() else: QTableView.mousePressEvent(self, event) else: self.clearSelection() event.accept()
python
def mousePressEvent(self, event): """Reimplement Qt method""" if event.button() != Qt.LeftButton: QTableView.mousePressEvent(self, event) return index_clicked = self.indexAt(event.pos()) if index_clicked.isValid(): if index_clicked == self.currentIndex() \ and index_clicked in self.selectedIndexes(): self.clearSelection() else: QTableView.mousePressEvent(self, event) else: self.clearSelection() event.accept()
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "button", "(", ")", "!=", "Qt", ".", "LeftButton", ":", "QTableView", ".", "mousePressEvent", "(", "self", ",", "event", ")", "return", "index_clicked", "=", "self", ".", "indexAt", "(", "event", ".", "pos", "(", ")", ")", "if", "index_clicked", ".", "isValid", "(", ")", ":", "if", "index_clicked", "==", "self", ".", "currentIndex", "(", ")", "and", "index_clicked", "in", "self", ".", "selectedIndexes", "(", ")", ":", "self", ".", "clearSelection", "(", ")", "else", ":", "QTableView", ".", "mousePressEvent", "(", "self", ",", "event", ")", "else", ":", "self", ".", "clearSelection", "(", ")", "event", ".", "accept", "(", ")" ]
Reimplement Qt method
[ "Reimplement", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L926-L940
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.mouseDoubleClickEvent
def mouseDoubleClickEvent(self, event): """Reimplement Qt method""" index_clicked = self.indexAt(event.pos()) if index_clicked.isValid(): row = index_clicked.row() # TODO: Remove hard coded "Value" column number (3 here) index_clicked = index_clicked.child(row, 3) self.edit(index_clicked) else: event.accept()
python
def mouseDoubleClickEvent(self, event): """Reimplement Qt method""" index_clicked = self.indexAt(event.pos()) if index_clicked.isValid(): row = index_clicked.row() # TODO: Remove hard coded "Value" column number (3 here) index_clicked = index_clicked.child(row, 3) self.edit(index_clicked) else: event.accept()
[ "def", "mouseDoubleClickEvent", "(", "self", ",", "event", ")", ":", "index_clicked", "=", "self", ".", "indexAt", "(", "event", ".", "pos", "(", ")", ")", "if", "index_clicked", ".", "isValid", "(", ")", ":", "row", "=", "index_clicked", ".", "row", "(", ")", "# TODO: Remove hard coded \"Value\" column number (3 here)\r", "index_clicked", "=", "index_clicked", ".", "child", "(", "row", ",", "3", ")", "self", ".", "edit", "(", "index_clicked", ")", "else", ":", "event", ".", "accept", "(", ")" ]
Reimplement Qt method
[ "Reimplement", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L942-L951
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.keyPressEvent
def keyPressEvent(self, event): """Reimplement Qt methods""" if event.key() == Qt.Key_Delete: self.remove_item() elif event.key() == Qt.Key_F2: self.rename_item() elif event == QKeySequence.Copy: self.copy() elif event == QKeySequence.Paste: self.paste() else: QTableView.keyPressEvent(self, event)
python
def keyPressEvent(self, event): """Reimplement Qt methods""" if event.key() == Qt.Key_Delete: self.remove_item() elif event.key() == Qt.Key_F2: self.rename_item() elif event == QKeySequence.Copy: self.copy() elif event == QKeySequence.Paste: self.paste() else: QTableView.keyPressEvent(self, event)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Delete", ":", "self", ".", "remove_item", "(", ")", "elif", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_F2", ":", "self", ".", "rename_item", "(", ")", "elif", "event", "==", "QKeySequence", ".", "Copy", ":", "self", ".", "copy", "(", ")", "elif", "event", "==", "QKeySequence", ".", "Paste", ":", "self", ".", "paste", "(", ")", "else", ":", "QTableView", ".", "keyPressEvent", "(", "self", ",", "event", ")" ]
Reimplement Qt methods
[ "Reimplement", "Qt", "methods" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L953-L964
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.contextMenuEvent
def contextMenuEvent(self, event): """Reimplement Qt method""" if self.model.showndata: self.refresh_menu() self.menu.popup(event.globalPos()) event.accept() else: self.empty_ws_menu.popup(event.globalPos()) event.accept()
python
def contextMenuEvent(self, event): """Reimplement Qt method""" if self.model.showndata: self.refresh_menu() self.menu.popup(event.globalPos()) event.accept() else: self.empty_ws_menu.popup(event.globalPos()) event.accept()
[ "def", "contextMenuEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "model", ".", "showndata", ":", "self", ".", "refresh_menu", "(", ")", "self", ".", "menu", ".", "popup", "(", "event", ".", "globalPos", "(", ")", ")", "event", ".", "accept", "(", ")", "else", ":", "self", ".", "empty_ws_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/collectionseditor.py#L966-L974
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.dragEnterEvent
def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore()
python
def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore()
[ "def", "dragEnterEvent", "(", "self", ",", "event", ")", ":", "if", "mimedata2url", "(", "event", ".", "mimeData", "(", ")", ")", ":", "event", ".", "accept", "(", ")", "else", ":", "event", ".", "ignore", "(", ")" ]
Allow user to drag files
[ "Allow", "user", "to", "drag", "files" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L976-L981
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.dragMoveEvent
def dragMoveEvent(self, event): """Allow user to move files""" if mimedata2url(event.mimeData()): event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore()
python
def dragMoveEvent(self, event): """Allow user to move files""" if mimedata2url(event.mimeData()): event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore()
[ "def", "dragMoveEvent", "(", "self", ",", "event", ")", ":", "if", "mimedata2url", "(", "event", ".", "mimeData", "(", ")", ")", ":", "event", ".", "setDropAction", "(", "Qt", ".", "CopyAction", ")", "event", ".", "accept", "(", ")", "else", ":", "event", ".", "ignore", "(", ")" ]
Allow user to move files
[ "Allow", "user", "to", "move", "files" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L983-L989
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.dropEvent
def dropEvent(self, event): """Allow user to drop supported files""" urls = mimedata2url(event.mimeData()) if urls: event.setDropAction(Qt.CopyAction) event.accept() self.sig_files_dropped.emit(urls) else: event.ignore()
python
def dropEvent(self, event): """Allow user to drop supported files""" urls = mimedata2url(event.mimeData()) if urls: event.setDropAction(Qt.CopyAction) event.accept() self.sig_files_dropped.emit(urls) else: event.ignore()
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "urls", "=", "mimedata2url", "(", "event", ".", "mimeData", "(", ")", ")", "if", "urls", ":", "event", ".", "setDropAction", "(", "Qt", ".", "CopyAction", ")", "event", ".", "accept", "(", ")", "self", ".", "sig_files_dropped", ".", "emit", "(", "urls", ")", "else", ":", "event", ".", "ignore", "(", ")" ]
Allow user to drop supported files
[ "Allow", "user", "to", "drop", "supported", "files" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L991-L999
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.toggle_minmax
def toggle_minmax(self, state): """Toggle min/max display for numpy arrays""" self.sig_option_changed.emit('minmax', state) self.model.minmax = state
python
def toggle_minmax(self, state): """Toggle min/max display for numpy arrays""" self.sig_option_changed.emit('minmax', state) self.model.minmax = state
[ "def", "toggle_minmax", "(", "self", ",", "state", ")", ":", "self", ".", "sig_option_changed", ".", "emit", "(", "'minmax'", ",", "state", ")", "self", ".", "model", ".", "minmax", "=", "state" ]
Toggle min/max display for numpy arrays
[ "Toggle", "min", "/", "max", "display", "for", "numpy", "arrays" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1002-L1005
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.set_dataframe_format
def set_dataframe_format(self, new_format): """ Set format to use in DataframeEditor. Args: new_format (string): e.g. "%.3f" """ self.sig_option_changed.emit('dataframe_format', new_format) self.model.dataframe_format = new_format
python
def set_dataframe_format(self, new_format): """ Set format to use in DataframeEditor. Args: new_format (string): e.g. "%.3f" """ self.sig_option_changed.emit('dataframe_format', new_format) self.model.dataframe_format = new_format
[ "def", "set_dataframe_format", "(", "self", ",", "new_format", ")", ":", "self", ".", "sig_option_changed", ".", "emit", "(", "'dataframe_format'", ",", "new_format", ")", "self", ".", "model", ".", "dataframe_format", "=", "new_format" ]
Set format to use in DataframeEditor. Args: new_format (string): e.g. "%.3f"
[ "Set", "format", "to", "use", "in", "DataframeEditor", ".", "Args", ":", "new_format", "(", "string", ")", ":", "e", ".", "g", ".", "%", ".", "3f" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1008-L1016
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.edit_item
def edit_item(self): """Edit item""" index = self.currentIndex() if not index.isValid(): return # TODO: Remove hard coded "Value" column number (3 here) self.edit(index.child(index.row(), 3))
python
def edit_item(self): """Edit item""" index = self.currentIndex() if not index.isValid(): return # TODO: Remove hard coded "Value" column number (3 here) self.edit(index.child(index.row(), 3))
[ "def", "edit_item", "(", "self", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "# TODO: Remove hard coded \"Value\" column number (3 here)\r", "self", ".", "edit", "(", "index", ".", "child", "(", "index", ".", "row", "(", ")", ",", "3", ")", ")" ]
Edit item
[ "Edit", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1019-L1025
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.remove_item
def remove_item(self): """Remove item""" indexes = self.selectedIndexes() if not indexes: return for index in indexes: if not index.isValid(): return one = _("Do you want to remove the selected item?") more = _("Do you want to remove all selected items?") answer = QMessageBox.question(self, _( "Remove"), one if len(indexes) == 1 else more, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: idx_rows = unsorted_unique([idx.row() for idx in indexes]) keys = [ self.model.keys[idx_row] for idx_row in idx_rows ] self.remove_values(keys)
python
def remove_item(self): """Remove item""" indexes = self.selectedIndexes() if not indexes: return for index in indexes: if not index.isValid(): return one = _("Do you want to remove the selected item?") more = _("Do you want to remove all selected items?") answer = QMessageBox.question(self, _( "Remove"), one if len(indexes) == 1 else more, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: idx_rows = unsorted_unique([idx.row() for idx in indexes]) keys = [ self.model.keys[idx_row] for idx_row in idx_rows ] self.remove_values(keys)
[ "def", "remove_item", "(", "self", ")", ":", "indexes", "=", "self", ".", "selectedIndexes", "(", ")", "if", "not", "indexes", ":", "return", "for", "index", "in", "indexes", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "one", "=", "_", "(", "\"Do you want to remove the selected item?\"", ")", "more", "=", "_", "(", "\"Do you want to remove all selected items?\"", ")", "answer", "=", "QMessageBox", ".", "question", "(", "self", ",", "_", "(", "\"Remove\"", ")", ",", "one", "if", "len", "(", "indexes", ")", "==", "1", "else", "more", ",", "QMessageBox", ".", "Yes", "|", "QMessageBox", ".", "No", ")", "if", "answer", "==", "QMessageBox", ".", "Yes", ":", "idx_rows", "=", "unsorted_unique", "(", "[", "idx", ".", "row", "(", ")", "for", "idx", "in", "indexes", "]", ")", "keys", "=", "[", "self", ".", "model", ".", "keys", "[", "idx_row", "]", "for", "idx_row", "in", "idx_rows", "]", "self", ".", "remove_values", "(", "keys", ")" ]
Remove item
[ "Remove", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1028-L1044
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.copy_item
def copy_item(self, erase_original=False): """Copy item""" indexes = self.selectedIndexes() if not indexes: return idx_rows = unsorted_unique([idx.row() for idx in indexes]) if len(idx_rows) > 1 or not indexes[0].isValid(): return orig_key = self.model.keys[idx_rows[0]] if erase_original: title = _('Rename') field_text = _('New variable name:') else: title = _('Duplicate') field_text = _('Variable name:') data = self.model.get_data() if isinstance(data, (list, set)): new_key, valid = len(data), True else: new_key, valid = QInputDialog.getText(self, title, field_text, QLineEdit.Normal, orig_key) if valid and to_text_string(new_key): new_key = try_to_eval(to_text_string(new_key)) if new_key == orig_key: return self.copy_value(orig_key, new_key) if erase_original: self.remove_values([orig_key])
python
def copy_item(self, erase_original=False): """Copy item""" indexes = self.selectedIndexes() if not indexes: return idx_rows = unsorted_unique([idx.row() for idx in indexes]) if len(idx_rows) > 1 or not indexes[0].isValid(): return orig_key = self.model.keys[idx_rows[0]] if erase_original: title = _('Rename') field_text = _('New variable name:') else: title = _('Duplicate') field_text = _('Variable name:') data = self.model.get_data() if isinstance(data, (list, set)): new_key, valid = len(data), True else: new_key, valid = QInputDialog.getText(self, title, field_text, QLineEdit.Normal, orig_key) if valid and to_text_string(new_key): new_key = try_to_eval(to_text_string(new_key)) if new_key == orig_key: return self.copy_value(orig_key, new_key) if erase_original: self.remove_values([orig_key])
[ "def", "copy_item", "(", "self", ",", "erase_original", "=", "False", ")", ":", "indexes", "=", "self", ".", "selectedIndexes", "(", ")", "if", "not", "indexes", ":", "return", "idx_rows", "=", "unsorted_unique", "(", "[", "idx", ".", "row", "(", ")", "for", "idx", "in", "indexes", "]", ")", "if", "len", "(", "idx_rows", ")", ">", "1", "or", "not", "indexes", "[", "0", "]", ".", "isValid", "(", ")", ":", "return", "orig_key", "=", "self", ".", "model", ".", "keys", "[", "idx_rows", "[", "0", "]", "]", "if", "erase_original", ":", "title", "=", "_", "(", "'Rename'", ")", "field_text", "=", "_", "(", "'New variable name:'", ")", "else", ":", "title", "=", "_", "(", "'Duplicate'", ")", "field_text", "=", "_", "(", "'Variable name:'", ")", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "if", "isinstance", "(", "data", ",", "(", "list", ",", "set", ")", ")", ":", "new_key", ",", "valid", "=", "len", "(", "data", ")", ",", "True", "else", ":", "new_key", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "title", ",", "field_text", ",", "QLineEdit", ".", "Normal", ",", "orig_key", ")", "if", "valid", "and", "to_text_string", "(", "new_key", ")", ":", "new_key", "=", "try_to_eval", "(", "to_text_string", "(", "new_key", ")", ")", "if", "new_key", "==", "orig_key", ":", "return", "self", ".", "copy_value", "(", "orig_key", ",", "new_key", ")", "if", "erase_original", ":", "self", ".", "remove_values", "(", "[", "orig_key", "]", ")" ]
Copy item
[ "Copy", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1046-L1073
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.insert_item
def insert_item(self): """Insert item""" index = self.currentIndex() if not index.isValid(): row = self.model.rowCount() else: row = index.row() data = self.model.get_data() if isinstance(data, list): key = row data.insert(row, '') elif isinstance(data, dict): key, valid = QInputDialog.getText(self, _( 'Insert'), _( 'Key:'), QLineEdit.Normal) if valid and to_text_string(key): key = try_to_eval(to_text_string(key)) else: return else: return value, valid = QInputDialog.getText(self, _('Insert'), _('Value:'), QLineEdit.Normal) if valid and to_text_string(value): self.new_value(key, try_to_eval(to_text_string(value)))
python
def insert_item(self): """Insert item""" index = self.currentIndex() if not index.isValid(): row = self.model.rowCount() else: row = index.row() data = self.model.get_data() if isinstance(data, list): key = row data.insert(row, '') elif isinstance(data, dict): key, valid = QInputDialog.getText(self, _( 'Insert'), _( 'Key:'), QLineEdit.Normal) if valid and to_text_string(key): key = try_to_eval(to_text_string(key)) else: return else: return value, valid = QInputDialog.getText(self, _('Insert'), _('Value:'), QLineEdit.Normal) if valid and to_text_string(value): self.new_value(key, try_to_eval(to_text_string(value)))
[ "def", "insert_item", "(", "self", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "if", "not", "index", ".", "isValid", "(", ")", ":", "row", "=", "self", ".", "model", ".", "rowCount", "(", ")", "else", ":", "row", "=", "index", ".", "row", "(", ")", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "key", "=", "row", "data", ".", "insert", "(", "row", ",", "''", ")", "elif", "isinstance", "(", "data", ",", "dict", ")", ":", "key", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'Insert'", ")", ",", "_", "(", "'Key:'", ")", ",", "QLineEdit", ".", "Normal", ")", "if", "valid", "and", "to_text_string", "(", "key", ")", ":", "key", "=", "try_to_eval", "(", "to_text_string", "(", "key", ")", ")", "else", ":", "return", "else", ":", "return", "value", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'Insert'", ")", ",", "_", "(", "'Value:'", ")", ",", "QLineEdit", ".", "Normal", ")", "if", "valid", "and", "to_text_string", "(", "value", ")", ":", "self", ".", "new_value", "(", "key", ",", "try_to_eval", "(", "to_text_string", "(", "value", ")", ")", ")" ]
Insert item
[ "Insert", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1086-L1109
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.plot_item
def plot_item(self, funcname): """Plot item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: self.plot(key, funcname) except (ValueError, TypeError) as error: QMessageBox.critical(self, _( "Plot"), _("<b>Unable to plot data.</b>" "<br><br>Error message:<br>%s" ) % str(error))
python
def plot_item(self, funcname): """Plot item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: self.plot(key, funcname) except (ValueError, TypeError) as error: QMessageBox.critical(self, _( "Plot"), _("<b>Unable to plot data.</b>" "<br><br>Error message:<br>%s" ) % str(error))
[ "def", "plot_item", "(", "self", ",", "funcname", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "if", "self", ".", "__prepare_plot", "(", ")", ":", "key", "=", "self", ".", "model", ".", "get_key", "(", "index", ")", "try", ":", "self", ".", "plot", "(", "key", ",", "funcname", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "error", ":", "QMessageBox", ".", "critical", "(", "self", ",", "_", "(", "\"Plot\"", ")", ",", "_", "(", "\"<b>Unable to plot data.</b>\"", "\"<br><br>Error message:<br>%s\"", ")", "%", "str", "(", "error", ")", ")" ]
Plot item
[ "Plot", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1126-L1137
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.imshow_item
def imshow_item(self): """Imshow item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: if self.is_image(key): self.show_image(key) else: self.imshow(key) except (ValueError, TypeError) as error: QMessageBox.critical(self, _( "Plot"), _("<b>Unable to show image.</b>" "<br><br>Error message:<br>%s" ) % str(error))
python
def imshow_item(self): """Imshow item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: if self.is_image(key): self.show_image(key) else: self.imshow(key) except (ValueError, TypeError) as error: QMessageBox.critical(self, _( "Plot"), _("<b>Unable to show image.</b>" "<br><br>Error message:<br>%s" ) % str(error))
[ "def", "imshow_item", "(", "self", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "if", "self", ".", "__prepare_plot", "(", ")", ":", "key", "=", "self", ".", "model", ".", "get_key", "(", "index", ")", "try", ":", "if", "self", ".", "is_image", "(", "key", ")", ":", "self", ".", "show_image", "(", "key", ")", "else", ":", "self", ".", "imshow", "(", "key", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "error", ":", "QMessageBox", ".", "critical", "(", "self", ",", "_", "(", "\"Plot\"", ")", ",", "_", "(", "\"<b>Unable to show image.</b>\"", "\"<br><br>Error message:<br>%s\"", ")", "%", "str", "(", "error", ")", ")" ]
Imshow item
[ "Imshow", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1140-L1154
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.save_array
def save_array(self): """Save array""" title = _( "Save array") if self.array_filename is None: self.array_filename = getcwd_or_home() self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, self.array_filename, _("NumPy arrays")+" (*.npy)") self.redirect_stdio.emit(True) if filename: self.array_filename = filename data = self.delegate.get_value( self.currentIndex() ) try: import numpy as np np.save(self.array_filename, data) except Exception as error: QMessageBox.critical(self, title, _("<b>Unable to save array</b>" "<br><br>Error message:<br>%s" ) % str(error))
python
def save_array(self): """Save array""" title = _( "Save array") if self.array_filename is None: self.array_filename = getcwd_or_home() self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, self.array_filename, _("NumPy arrays")+" (*.npy)") self.redirect_stdio.emit(True) if filename: self.array_filename = filename data = self.delegate.get_value( self.currentIndex() ) try: import numpy as np np.save(self.array_filename, data) except Exception as error: QMessageBox.critical(self, title, _("<b>Unable to save array</b>" "<br><br>Error message:<br>%s" ) % str(error))
[ "def", "save_array", "(", "self", ")", ":", "title", "=", "_", "(", "\"Save array\"", ")", "if", "self", ".", "array_filename", "is", "None", ":", "self", ".", "array_filename", "=", "getcwd_or_home", "(", ")", "self", ".", "redirect_stdio", ".", "emit", "(", "False", ")", "filename", ",", "_selfilter", "=", "getsavefilename", "(", "self", ",", "title", ",", "self", ".", "array_filename", ",", "_", "(", "\"NumPy arrays\"", ")", "+", "\" (*.npy)\"", ")", "self", ".", "redirect_stdio", ".", "emit", "(", "True", ")", "if", "filename", ":", "self", ".", "array_filename", "=", "filename", "data", "=", "self", ".", "delegate", ".", "get_value", "(", "self", ".", "currentIndex", "(", ")", ")", "try", ":", "import", "numpy", "as", "np", "np", ".", "save", "(", "self", ".", "array_filename", ",", "data", ")", "except", "Exception", "as", "error", ":", "QMessageBox", ".", "critical", "(", "self", ",", "title", ",", "_", "(", "\"<b>Unable to save array</b>\"", "\"<br><br>Error message:<br>%s\"", ")", "%", "str", "(", "error", ")", ")" ]
Save array
[ "Save", "array" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1157-L1177
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.copy
def copy(self): """Copy text to clipboard""" clipboard = QApplication.clipboard() clipl = [] for idx in self.selectedIndexes(): if not idx.isValid(): continue obj = self.delegate.get_value(idx) # Check if we are trying to copy a numpy array, and if so make sure # to copy the whole thing in a tab separated format if isinstance(obj, (ndarray, MaskedArray)) \ and ndarray is not FakeObject: if PY3: output = io.BytesIO() else: output = io.StringIO() try: np_savetxt(output, obj, delimiter='\t') except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy " "this array")) return obj = output.getvalue().decode('utf-8') output.close() elif isinstance(obj, (DataFrame, Series)) \ and DataFrame is not FakeObject: output = io.StringIO() try: obj.to_csv(output, sep='\t', index=True, header=True) except Exception: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy " "this dataframe")) return if PY3: obj = output.getvalue() else: obj = output.getvalue().decode('utf-8') output.close() elif is_binary_string(obj): obj = to_text_string(obj, 'utf8') else: obj = to_text_string(obj) clipl.append(obj) clipboard.setText('\n'.join(clipl))
python
def copy(self): """Copy text to clipboard""" clipboard = QApplication.clipboard() clipl = [] for idx in self.selectedIndexes(): if not idx.isValid(): continue obj = self.delegate.get_value(idx) # Check if we are trying to copy a numpy array, and if so make sure # to copy the whole thing in a tab separated format if isinstance(obj, (ndarray, MaskedArray)) \ and ndarray is not FakeObject: if PY3: output = io.BytesIO() else: output = io.StringIO() try: np_savetxt(output, obj, delimiter='\t') except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy " "this array")) return obj = output.getvalue().decode('utf-8') output.close() elif isinstance(obj, (DataFrame, Series)) \ and DataFrame is not FakeObject: output = io.StringIO() try: obj.to_csv(output, sep='\t', index=True, header=True) except Exception: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy " "this dataframe")) return if PY3: obj = output.getvalue() else: obj = output.getvalue().decode('utf-8') output.close() elif is_binary_string(obj): obj = to_text_string(obj, 'utf8') else: obj = to_text_string(obj) clipl.append(obj) clipboard.setText('\n'.join(clipl))
[ "def", "copy", "(", "self", ")", ":", "clipboard", "=", "QApplication", ".", "clipboard", "(", ")", "clipl", "=", "[", "]", "for", "idx", "in", "self", ".", "selectedIndexes", "(", ")", ":", "if", "not", "idx", ".", "isValid", "(", ")", ":", "continue", "obj", "=", "self", ".", "delegate", ".", "get_value", "(", "idx", ")", "# Check if we are trying to copy a numpy array, and if so make sure\r", "# to copy the whole thing in a tab separated format\r", "if", "isinstance", "(", "obj", ",", "(", "ndarray", ",", "MaskedArray", ")", ")", "and", "ndarray", "is", "not", "FakeObject", ":", "if", "PY3", ":", "output", "=", "io", ".", "BytesIO", "(", ")", "else", ":", "output", "=", "io", ".", "StringIO", "(", ")", "try", ":", "np_savetxt", "(", "output", ",", "obj", ",", "delimiter", "=", "'\\t'", ")", "except", ":", "QMessageBox", ".", "warning", "(", "self", ",", "_", "(", "\"Warning\"", ")", ",", "_", "(", "\"It was not possible to copy \"", "\"this array\"", ")", ")", "return", "obj", "=", "output", ".", "getvalue", "(", ")", ".", "decode", "(", "'utf-8'", ")", "output", ".", "close", "(", ")", "elif", "isinstance", "(", "obj", ",", "(", "DataFrame", ",", "Series", ")", ")", "and", "DataFrame", "is", "not", "FakeObject", ":", "output", "=", "io", ".", "StringIO", "(", ")", "try", ":", "obj", ".", "to_csv", "(", "output", ",", "sep", "=", "'\\t'", ",", "index", "=", "True", ",", "header", "=", "True", ")", "except", "Exception", ":", "QMessageBox", ".", "warning", "(", "self", ",", "_", "(", "\"Warning\"", ")", ",", "_", "(", "\"It was not possible to copy \"", "\"this dataframe\"", ")", ")", "return", "if", "PY3", ":", "obj", "=", "output", ".", "getvalue", "(", ")", "else", ":", "obj", "=", "output", ".", "getvalue", "(", ")", ".", "decode", "(", "'utf-8'", ")", "output", ".", "close", "(", ")", "elif", "is_binary_string", "(", "obj", ")", ":", "obj", "=", "to_text_string", "(", "obj", ",", "'utf8'", ")", "else", ":", "obj", "=", "to_text_string", "(", "obj", ")", "clipl", ".", "append", "(", "obj", ")", "clipboard", ".", "setText", "(", "'\\n'", ".", "join", "(", "clipl", ")", ")" ]
Copy text to clipboard
[ "Copy", "text", "to", "clipboard" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1180-L1225
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.import_from_string
def import_from_string(self, text, title=None): """Import data from string""" data = self.model.get_data() # Check if data is a dict if not hasattr(data, "keys"): return editor = ImportWizard(self, text, title=title, contents_title=_("Clipboard contents"), varname=fix_reference_name("data", blacklist=list(data.keys()))) if editor.exec_(): var_name, clip_data = editor.get_data() self.new_value(var_name, clip_data)
python
def import_from_string(self, text, title=None): """Import data from string""" data = self.model.get_data() # Check if data is a dict if not hasattr(data, "keys"): return editor = ImportWizard(self, text, title=title, contents_title=_("Clipboard contents"), varname=fix_reference_name("data", blacklist=list(data.keys()))) if editor.exec_(): var_name, clip_data = editor.get_data() self.new_value(var_name, clip_data)
[ "def", "import_from_string", "(", "self", ",", "text", ",", "title", "=", "None", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "# Check if data is a dict\r", "if", "not", "hasattr", "(", "data", ",", "\"keys\"", ")", ":", "return", "editor", "=", "ImportWizard", "(", "self", ",", "text", ",", "title", "=", "title", ",", "contents_title", "=", "_", "(", "\"Clipboard contents\"", ")", ",", "varname", "=", "fix_reference_name", "(", "\"data\"", ",", "blacklist", "=", "list", "(", "data", ".", "keys", "(", ")", ")", ")", ")", "if", "editor", ".", "exec_", "(", ")", ":", "var_name", ",", "clip_data", "=", "editor", ".", "get_data", "(", ")", "self", ".", "new_value", "(", "var_name", ",", "clip_data", ")" ]
Import data from string
[ "Import", "data", "from", "string" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1227-L1239
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
BaseTableView.paste
def paste(self): """Import text/data/code from clipboard""" clipboard = QApplication.clipboard() cliptext = '' if clipboard.mimeData().hasText(): cliptext = to_text_string(clipboard.text()) if cliptext.strip(): self.import_from_string(cliptext, title=_("Import from clipboard")) else: QMessageBox.warning(self, _( "Empty clipboard"), _("Nothing to be imported from clipboard."))
python
def paste(self): """Import text/data/code from clipboard""" clipboard = QApplication.clipboard() cliptext = '' if clipboard.mimeData().hasText(): cliptext = to_text_string(clipboard.text()) if cliptext.strip(): self.import_from_string(cliptext, title=_("Import from clipboard")) else: QMessageBox.warning(self, _( "Empty clipboard"), _("Nothing to be imported from clipboard."))
[ "def", "paste", "(", "self", ")", ":", "clipboard", "=", "QApplication", ".", "clipboard", "(", ")", "cliptext", "=", "''", "if", "clipboard", ".", "mimeData", "(", ")", ".", "hasText", "(", ")", ":", "cliptext", "=", "to_text_string", "(", "clipboard", ".", "text", "(", ")", ")", "if", "cliptext", ".", "strip", "(", ")", ":", "self", ".", "import_from_string", "(", "cliptext", ",", "title", "=", "_", "(", "\"Import from clipboard\"", ")", ")", "else", ":", "QMessageBox", ".", "warning", "(", "self", ",", "_", "(", "\"Empty clipboard\"", ")", ",", "_", "(", "\"Nothing to be imported from clipboard.\"", ")", ")" ]
Import text/data/code from clipboard
[ "Import", "text", "/", "data", "/", "code", "from", "clipboard" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1242-L1252
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.remove_values
def remove_values(self, keys): """Remove values from data""" data = self.model.get_data() for key in sorted(keys, reverse=True): data.pop(key) self.set_data(data)
python
def remove_values(self, keys): """Remove values from data""" data = self.model.get_data() for key in sorted(keys, reverse=True): data.pop(key) self.set_data(data)
[ "def", "remove_values", "(", "self", ",", "keys", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "for", "key", "in", "sorted", "(", "keys", ",", "reverse", "=", "True", ")", ":", "data", ".", "pop", "(", "key", ")", "self", ".", "set_data", "(", "data", ")" ]
Remove values from data
[ "Remove", "values", "from", "data" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1277-L1282
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.copy_value
def copy_value(self, orig_key, new_key): """Copy value""" data = self.model.get_data() if isinstance(data, list): data.append(data[orig_key]) if isinstance(data, set): data.add(data[orig_key]) else: data[new_key] = data[orig_key] self.set_data(data)
python
def copy_value(self, orig_key, new_key): """Copy value""" data = self.model.get_data() if isinstance(data, list): data.append(data[orig_key]) if isinstance(data, set): data.add(data[orig_key]) else: data[new_key] = data[orig_key] self.set_data(data)
[ "def", "copy_value", "(", "self", ",", "orig_key", ",", "new_key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "data", ".", "append", "(", "data", "[", "orig_key", "]", ")", "if", "isinstance", "(", "data", ",", "set", ")", ":", "data", ".", "add", "(", "data", "[", "orig_key", "]", ")", "else", ":", "data", "[", "new_key", "]", "=", "data", "[", "orig_key", "]", "self", ".", "set_data", "(", "data", ")" ]
Copy value
[ "Copy", "value" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1284-L1293
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.new_value
def new_value(self, key, value): """Create new value in data""" data = self.model.get_data() data[key] = value self.set_data(data)
python
def new_value(self, key, value): """Create new value in data""" data = self.model.get_data() data[key] = value self.set_data(data)
[ "def", "new_value", "(", "self", ",", "key", ",", "value", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "data", "[", "key", "]", "=", "value", "self", ".", "set_data", "(", "data", ")" ]
Create new value in data
[ "Create", "new", "value", "in", "data" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1295-L1299
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.is_list
def is_list(self, key): """Return True if variable is a list or a tuple""" data = self.model.get_data() return isinstance(data[key], (tuple, list))
python
def is_list(self, key): """Return True if variable is a list or a tuple""" data = self.model.get_data() return isinstance(data[key], (tuple, list))
[ "def", "is_list", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "isinstance", "(", "data", "[", "key", "]", ",", "(", "tuple", ",", "list", ")", ")" ]
Return True if variable is a list or a tuple
[ "Return", "True", "if", "variable", "is", "a", "list", "or", "a", "tuple" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1301-L1304
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.is_set
def is_set(self, key): """Return True if variable is a set""" data = self.model.get_data() return isinstance(data[key], set)
python
def is_set(self, key): """Return True if variable is a set""" data = self.model.get_data() return isinstance(data[key], set)
[ "def", "is_set", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "isinstance", "(", "data", "[", "key", "]", ",", "set", ")" ]
Return True if variable is a set
[ "Return", "True", "if", "variable", "is", "a", "set" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1306-L1309
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.get_len
def get_len(self, key): """Return sequence length""" data = self.model.get_data() return len(data[key])
python
def get_len(self, key): """Return sequence length""" data = self.model.get_data() return len(data[key])
[ "def", "get_len", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "len", "(", "data", "[", "key", "]", ")" ]
Return sequence length
[ "Return", "sequence", "length" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1311-L1314
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.is_array
def is_array(self, key): """Return True if variable is a numpy array""" data = self.model.get_data() return isinstance(data[key], (ndarray, MaskedArray))
python
def is_array(self, key): """Return True if variable is a numpy array""" data = self.model.get_data() return isinstance(data[key], (ndarray, MaskedArray))
[ "def", "is_array", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "isinstance", "(", "data", "[", "key", "]", ",", "(", "ndarray", ",", "MaskedArray", ")", ")" ]
Return True if variable is a numpy array
[ "Return", "True", "if", "variable", "is", "a", "numpy", "array" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1316-L1319
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.is_image
def is_image(self, key): """Return True if variable is a PIL.Image image""" data = self.model.get_data() return isinstance(data[key], Image)
python
def is_image(self, key): """Return True if variable is a PIL.Image image""" data = self.model.get_data() return isinstance(data[key], Image)
[ "def", "is_image", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "isinstance", "(", "data", "[", "key", "]", ",", "Image", ")" ]
Return True if variable is a PIL.Image image
[ "Return", "True", "if", "variable", "is", "a", "PIL", ".", "Image", "image" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1321-L1324
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.is_dict
def is_dict(self, key): """Return True if variable is a dictionary""" data = self.model.get_data() return isinstance(data[key], dict)
python
def is_dict(self, key): """Return True if variable is a dictionary""" data = self.model.get_data() return isinstance(data[key], dict)
[ "def", "is_dict", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "isinstance", "(", "data", "[", "key", "]", ",", "dict", ")" ]
Return True if variable is a dictionary
[ "Return", "True", "if", "variable", "is", "a", "dictionary" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1326-L1329
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.get_array_shape
def get_array_shape(self, key): """Return array's shape""" data = self.model.get_data() return data[key].shape
python
def get_array_shape(self, key): """Return array's shape""" data = self.model.get_data() return data[key].shape
[ "def", "get_array_shape", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "data", "[", "key", "]", ".", "shape" ]
Return array's shape
[ "Return", "array", "s", "shape" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1331-L1334
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.get_array_ndim
def get_array_ndim(self, key): """Return array's ndim""" data = self.model.get_data() return data[key].ndim
python
def get_array_ndim(self, key): """Return array's ndim""" data = self.model.get_data() return data[key].ndim
[ "def", "get_array_ndim", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "data", "[", "key", "]", ".", "ndim" ]
Return array's ndim
[ "Return", "array", "s", "ndim" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1336-L1339
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.oedit
def oedit(self, key): """Edit item""" data = self.model.get_data() from spyder.plugins.variableexplorer.widgets.objecteditor import ( oedit) oedit(data[key])
python
def oedit(self, key): """Edit item""" data = self.model.get_data() from spyder.plugins.variableexplorer.widgets.objecteditor import ( oedit) oedit(data[key])
[ "def", "oedit", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "from", "spyder", ".", "plugins", ".", "variableexplorer", ".", "widgets", ".", "objecteditor", "import", "(", "oedit", ")", "oedit", "(", "data", "[", "key", "]", ")" ]
Edit item
[ "Edit", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1341-L1346
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.plot
def plot(self, key, funcname): """Plot item""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() getattr(plt, funcname)(data[key]) plt.show()
python
def plot(self, key, funcname): """Plot item""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() getattr(plt, funcname)(data[key]) plt.show()
[ "def", "plot", "(", "self", ",", "key", ",", "funcname", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "import", "spyder", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", ")", "getattr", "(", "plt", ",", "funcname", ")", "(", "data", "[", "key", "]", ")", "plt", ".", "show", "(", ")" ]
Plot item
[ "Plot", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1348-L1354
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.imshow
def imshow(self, key): """Show item's image""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() plt.imshow(data[key]) plt.show()
python
def imshow(self, key): """Show item's image""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() plt.imshow(data[key]) plt.show()
[ "def", "imshow", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "import", "spyder", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", ")", "plt", ".", "imshow", "(", "data", "[", "key", "]", ")", "plt", ".", "show", "(", ")" ]
Show item's image
[ "Show", "item", "s", "image" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1356-L1362
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.show_image
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
python
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
[ "def", "show_image", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "data", "[", "key", "]", ".", "show", "(", ")" ]
Show image (item is a PIL image)
[ "Show", "image", "(", "item", "is", "a", "PIL", "image", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1364-L1367
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditorTableView.refresh_menu
def refresh_menu(self): """Refresh context menu""" data = self.model.get_data() index = self.currentIndex() condition = (not isinstance(data, (tuple, set))) and index.isValid() \ and not self.readonly self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.insert_action.setEnabled( not self.readonly ) self.duplicate_action.setEnabled(condition) condition_rename = not isinstance(data, (tuple, list, set)) self.rename_action.setEnabled(condition_rename) self.refresh_plot_entries(index)
python
def refresh_menu(self): """Refresh context menu""" data = self.model.get_data() index = self.currentIndex() condition = (not isinstance(data, (tuple, set))) and index.isValid() \ and not self.readonly self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.insert_action.setEnabled( not self.readonly ) self.duplicate_action.setEnabled(condition) condition_rename = not isinstance(data, (tuple, list, set)) self.rename_action.setEnabled(condition_rename) self.refresh_plot_entries(index)
[ "def", "refresh_menu", "(", "self", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "index", "=", "self", ".", "currentIndex", "(", ")", "condition", "=", "(", "not", "isinstance", "(", "data", ",", "(", "tuple", ",", "set", ")", ")", ")", "and", "index", ".", "isValid", "(", ")", "and", "not", "self", ".", "readonly", "self", ".", "edit_action", ".", "setEnabled", "(", "condition", ")", "self", ".", "remove_action", ".", "setEnabled", "(", "condition", ")", "self", ".", "insert_action", ".", "setEnabled", "(", "not", "self", ".", "readonly", ")", "self", ".", "duplicate_action", ".", "setEnabled", "(", "condition", ")", "condition_rename", "=", "not", "isinstance", "(", "data", ",", "(", "tuple", ",", "list", ",", "set", ")", ")", "self", ".", "rename_action", ".", "setEnabled", "(", "condition_rename", ")", "self", ".", "refresh_plot_entries", "(", "index", ")" ]
Refresh context menu
[ "Refresh", "context", "menu" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1370-L1382
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
CollectionsEditor.setup
def setup(self, data, title='', readonly=False, width=650, remote=False, icon=None, parent=None): """Setup editor.""" if isinstance(data, (dict, set)): # dictionnary, set self.data_copy = data.copy() datalen = len(data) elif isinstance(data, (tuple, list)): # list, tuple self.data_copy = data[:] datalen = len(data) else: # unknown object import copy try: self.data_copy = copy.deepcopy(data) except NotImplementedError: self.data_copy = copy.copy(data) except (TypeError, AttributeError): readonly = True self.data_copy = data datalen = len(get_object_attrs(data)) # If the copy has a different type, then do not allow editing, because # this would change the type after saving; cf. issue #6936 if type(self.data_copy) != type(data): readonly = True self.widget = CollectionsEditorWidget(self, self.data_copy, title=title, readonly=readonly, remote=remote) self.widget.editor.model.sig_setting_data.connect( self.save_and_close_enable) layout = QVBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) # Buttons configuration btn_layout = QHBoxLayout() 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) layout.addLayout(btn_layout) constant = 121 row_height = 30 error_margin = 10 height = constant + row_height * min([10, datalen]) + error_margin self.resize(width, height) self.setWindowTitle(self.widget.get_title()) if icon is None: self.setWindowIcon(ima.icon('dictedit')) if sys.platform == 'darwin': # See: https://github.com/spyder-ide/spyder/issues/9051 self.setWindowFlags(Qt.Tool) else: # Make the dialog act as a window self.setWindowFlags(Qt.Window)
python
def setup(self, data, title='', readonly=False, width=650, remote=False, icon=None, parent=None): """Setup editor.""" if isinstance(data, (dict, set)): # dictionnary, set self.data_copy = data.copy() datalen = len(data) elif isinstance(data, (tuple, list)): # list, tuple self.data_copy = data[:] datalen = len(data) else: # unknown object import copy try: self.data_copy = copy.deepcopy(data) except NotImplementedError: self.data_copy = copy.copy(data) except (TypeError, AttributeError): readonly = True self.data_copy = data datalen = len(get_object_attrs(data)) # If the copy has a different type, then do not allow editing, because # this would change the type after saving; cf. issue #6936 if type(self.data_copy) != type(data): readonly = True self.widget = CollectionsEditorWidget(self, self.data_copy, title=title, readonly=readonly, remote=remote) self.widget.editor.model.sig_setting_data.connect( self.save_and_close_enable) layout = QVBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) # Buttons configuration btn_layout = QHBoxLayout() 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) layout.addLayout(btn_layout) constant = 121 row_height = 30 error_margin = 10 height = constant + row_height * min([10, datalen]) + error_margin self.resize(width, height) self.setWindowTitle(self.widget.get_title()) if icon is None: self.setWindowIcon(ima.icon('dictedit')) if sys.platform == 'darwin': # See: https://github.com/spyder-ide/spyder/issues/9051 self.setWindowFlags(Qt.Tool) else: # Make the dialog act as a window self.setWindowFlags(Qt.Window)
[ "def", "setup", "(", "self", ",", "data", ",", "title", "=", "''", ",", "readonly", "=", "False", ",", "width", "=", "650", ",", "remote", "=", "False", ",", "icon", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "(", "dict", ",", "set", ")", ")", ":", "# dictionnary, set\r", "self", ".", "data_copy", "=", "data", ".", "copy", "(", ")", "datalen", "=", "len", "(", "data", ")", "elif", "isinstance", "(", "data", ",", "(", "tuple", ",", "list", ")", ")", ":", "# list, tuple\r", "self", ".", "data_copy", "=", "data", "[", ":", "]", "datalen", "=", "len", "(", "data", ")", "else", ":", "# unknown object\r", "import", "copy", "try", ":", "self", ".", "data_copy", "=", "copy", ".", "deepcopy", "(", "data", ")", "except", "NotImplementedError", ":", "self", ".", "data_copy", "=", "copy", ".", "copy", "(", "data", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "readonly", "=", "True", "self", ".", "data_copy", "=", "data", "datalen", "=", "len", "(", "get_object_attrs", "(", "data", ")", ")", "# If the copy has a different type, then do not allow editing, because\r", "# this would change the type after saving; cf. issue #6936\r", "if", "type", "(", "self", ".", "data_copy", ")", "!=", "type", "(", "data", ")", ":", "readonly", "=", "True", "self", ".", "widget", "=", "CollectionsEditorWidget", "(", "self", ",", "self", ".", "data_copy", ",", "title", "=", "title", ",", "readonly", "=", "readonly", ",", "remote", "=", "remote", ")", "self", ".", "widget", ".", "editor", ".", "model", ".", "sig_setting_data", ".", "connect", "(", "self", ".", "save_and_close_enable", ")", "layout", "=", "QVBoxLayout", "(", ")", "layout", ".", "addWidget", "(", "self", ".", "widget", ")", "self", ".", "setLayout", "(", "layout", ")", "# Buttons configuration\r", "btn_layout", "=", "QHBoxLayout", "(", ")", "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", ")", "layout", ".", "addLayout", "(", "btn_layout", ")", "constant", "=", "121", "row_height", "=", "30", "error_margin", "=", "10", "height", "=", "constant", "+", "row_height", "*", "min", "(", "[", "10", ",", "datalen", "]", ")", "+", "error_margin", "self", ".", "resize", "(", "width", ",", "height", ")", "self", ".", "setWindowTitle", "(", "self", ".", "widget", ".", "get_title", "(", ")", ")", "if", "icon", "is", "None", ":", "self", ".", "setWindowIcon", "(", "ima", ".", "icon", "(", "'dictedit'", ")", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# See: https://github.com/spyder-ide/spyder/issues/9051\r", "self", ".", "setWindowFlags", "(", "Qt", ".", "Tool", ")", "else", ":", "# Make the dialog act as a window\r", "self", ".", "setWindowFlags", "(", "Qt", ".", "Window", ")" ]
Setup editor.
[ "Setup", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1427-L1497
train