INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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
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 = '' ...
Split source code into lines
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]
Split source code into python identifier - like tokens
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)]
Return the individual components of a given file path string ( for the local operating system ). Taken from https:// stackoverflow. com/ q/ 21498939/ 438386
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 wi...
Return the differentiated prefix of the given two iterables. Taken from https:// stackoverflow. com/ q/ 21498939/ 438386
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, elmt...
Get tab title without ambiguation.
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 ==...
Get a list of the path components of the files with the same name.
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_nam...
Add text decorations on a CodeEditor instance.
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) Ret...
Removes a text decoration from the editor.
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 Tr...
Update editor extra selections with added decorations.
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: ...
Order decorations according draw_order and size of selection.
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): ...
Get signature from inspect reply content
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 ...
Return True if object 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_impo...
Get object documentation dictionary
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_() ...
Reimplement call tips to only show signatures using the same style from our Editor and External Console too
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_head...
Encode parameters.
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(ar...
Encode object as json str.
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, de...
Generate 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 i...
In callback url: http:// host/ callback?code = 123&state = xyz
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: ...
Call function req and then send its results via ZMQ.
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 wrapp...
Class decorator that allows to map LSP method names to class methods.
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({...
Set model 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.shown...
Overriding sort method
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: ...
Array row number
def rowCount(self, index=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
Return current 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: ...
Background color depending on value
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: ...
Cell content
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 = va...
Overriding method 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"), _("Val...
Overriding method 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...
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....
Background color depending on value
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'] ...
Cell content change
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)...
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
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 TableMode...
Overriding method 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 variab...
Overriding method setEditorData Model -- > Editor
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_strin...
Overriding method setModelData Editor -- > Model
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()...
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)
Setup context 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.re...
Refresh context 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)
Set table 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)
Reimplement Qt method
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.curre...
Reimplement Qt method
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.chi...
Reimplement Qt methods
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.P...
Reimplement Qt method
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()
Allow user to drag files
def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore()
Allow user to move files
def dragMoveEvent(self, event): """Allow user to move files""" if mimedata2url(event.mimeData()): event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore()
Allow user to drop supported files
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()
Toggle min/ max display for numpy arrays
def toggle_minmax(self, state): """Toggle min/max display for numpy arrays""" self.sig_option_changed.emit('minmax', state) self.model.minmax = state
Set format to use in DataframeEditor. Args: new_format ( string ): e. g. %. 3f
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
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))
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...
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 ...
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 dat...
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.crit...
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.imsh...
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, ...
Copy text to clipboard
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...
Import data 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...
Import text/ data/ code from clipboard
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, titl...
Remove values from data
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)
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] ...
Create new value in data
def new_value(self, key, value): """Create new value in data""" data = self.model.get_data() data[key] = value self.set_data(data)
Return True if variable is a list or a tuple
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))
Return True if variable is a set
def is_set(self, key): """Return True if variable is a set""" data = self.model.get_data() return isinstance(data[key], set)
Return sequence length
def get_len(self, key): """Return sequence length""" data = self.model.get_data() return len(data[key])
Return True if variable is a numpy 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))
Return True if variable is a PIL. Image 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)
Return True if variable is a dictionary
def is_dict(self, key): """Return True if variable is a dictionary""" data = self.model.get_data() return isinstance(data[key], dict)
Return array s shape
def get_array_shape(self, key): """Return array's shape""" data = self.model.get_data() return data[key].shape
Return array s ndim
def get_array_ndim(self, key): """Return array's ndim""" data = self.model.get_data() return data[key].ndim
Edit item
def oedit(self, key): """Edit item""" data = self.model.get_data() from spyder.plugins.variableexplorer.widgets.objecteditor import ( oedit) oedit(data[key])
Plot item
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()
Show item s image
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()
Show image ( item is a PIL image )
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
Refresh context 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 ) sel...
Setup editor.
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(dat...
Handle the data change event to enable the save and close button.
def save_and_close_enable(self): """Handle the data change event to enable the save and close button.""" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True)
Get the value of a variable
def get_value(self, name): """Get the value of a variable""" value = self.shellwidget.get_value(name) # Reset temporal variable where value is saved to # save memory self.shellwidget._kernel_value = None return value
Create new value in data
def new_value(self, name, value): """Create new value in data""" try: # We need to enclose values in a list to be able to send # them to the kernel in Python 2 svalue = [cloudpickle.dumps(value, protocol=PICKLE_PROTOCOL)] # Needed to prevent memory...
Remove values from data
def remove_values(self, names): """Remove values from data""" for name in names: self.shellwidget.remove_value(name) self.shellwidget.refresh_namespacebrowser()
Copy value
def copy_value(self, orig_name, new_name): """Copy value""" self.shellwidget.copy_value(orig_name, new_name) self.shellwidget.refresh_namespacebrowser()
Plot item
def plot(self, name, funcname): """Plot item""" sw = self.shellwidget if sw._reading: sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name)) else: sw.execute("%%varexp --%s %s" % (funcname, name))
Show item s image
def imshow(self, name): """Show item's image""" sw = self.shellwidget if sw._reading: sw.dbg_exec_magic('varexp', '--imshow %s' % name) else: sw.execute("%%varexp --imshow %s" % name)
Show image ( item is a PIL image )
def show_image(self, name): """Show image (item is a PIL image)""" command = "%s.show()" % name sw = self.shellwidget if sw._reading: sw.kernel_client.input(command) else: sw.execute(command)
Get kernel id
def kernel_id(self): """Get kernel id""" if self.connection_file is not None: json_file = osp.basename(self.connection_file) return json_file.split('.json')[0]
Filename to save kernel stderr output.
def stderr_file(self): """Filename to save kernel stderr output.""" stderr_file = None if self.connection_file is not None: stderr_file = self.kernel_id + '.stderr' if self.stderr_dir is not None: stderr_file = osp.join(self.stderr_dir, stderr_file) ...
Get handle to stderr_file.
def stderr_handle(self): """Get handle to stderr_file.""" if self.stderr_file is not None: # Needed to prevent any error that could appear. # See issue 6267 try: handle = codecs.open(self.stderr_file, 'w', encoding='utf-8') except Ex...
Remove stderr_file associated with the client.
def remove_stderr_file(self): """Remove stderr_file associated with the client.""" try: # Defer closing the stderr_handle until the client # is closed because jupyter_client needs it open # while it tries to restart the kernel self.stderr_handle.clos...
Configure shellwidget after kernel is started
def configure_shellwidget(self, give_focus=True): """Configure shellwidget after kernel is started""" if give_focus: self.get_control().setFocus() # Set exit callback self.shellwidget.set_exit_callback() # To save history self.shellwidget.executing....
Method to handle what to do when the stop button is pressed
def stop_button_click_handler(self): """Method to handle what to do when the stop button is pressed""" self.stop_button.setDisabled(True) # Interrupt computations or stop debugging if not self.shellwidget._reading: self.interrupt_kernel() else: self...
Show kernel initialization errors in infowidget.
def show_kernel_error(self, error): """Show kernel initialization errors in infowidget.""" # Replace end of line chars with <br> eol = sourcecode.get_eol_chars(error) if eol: error = error.replace(eol, '<br>') # Don't break lines in hyphens # From htt...
Return client name
def get_name(self): """Return client name""" if self.given_name is None: # Name according to host if self.hostname is None: name = _("Console") else: name = self.hostname # Adding id to name client_id = ...
Return the text widget ( or similar ) to give focus to
def get_control(self): """Return the text widget (or similar) to give focus to""" # page_control is the widget used for paging page_control = self.shellwidget._page_control if page_control and page_control.isVisible(): return page_control else: retu...
Return options menu
def get_options_menu(self): """Return options menu""" env_action = create_action( self, _("Show environment variables"), icon=ima.icon('environ'), triggered=self.shellwidget.get_env ...
Return toolbar buttons list.
def get_toolbar_buttons(self): """Return toolbar buttons list.""" buttons = [] # Code to add the stop button if self.stop_button is None: self.stop_button = create_toolbutton( self, text=_("Stop"),...
Add actions to IPython widget context menu
def add_actions_to_context_menu(self, menu): """Add actions to IPython widget context menu""" inspect_action = create_action(self, _("Inspect current object"), QKeySequence(get_shortcut('console', 'inspect curren...
Set IPython widget s font
def set_font(self, font): """Set IPython widget's font""" self.shellwidget._control.setFont(font) self.shellwidget.font = font
Set IPython color scheme.
def set_color_scheme(self, color_scheme, reset=True): """Set IPython color scheme.""" # Needed to handle not initialized kernel_client # See issue 6996 try: self.shellwidget.set_color_scheme(color_scheme, reset) except AttributeError: pass
Shutdown kernel
def shutdown(self): """Shutdown kernel""" if self.get_kernel() is not None and not self.slave: self.shellwidget.kernel_manager.shutdown_kernel() if self.shellwidget.kernel_client is not None: background(self.shellwidget.kernel_client.stop_channels)
Restart the associated kernel. Took this code from the qtconsole project Licensed under the BSD license
def restart_kernel(self): """ Restart the associated kernel. Took this code from the qtconsole project Licensed under the BSD license """ sw = self.shellwidget if not running_under_pytest() and self.ask_before_restart: message = _('Are you ...