text
stringlengths
18
773k
def lint_fileset(*dirnames, **kwargs): """Lints a group of files using a given rcfile. Keyword arguments are * ``rc_filename`` (``str``): The name of the Pylint config RC file. * ``description`` (``str``): A description of the files and configuration currently being ru...
def make_rc(base_cfg, target_filename, additions=None, replacements=None): """Combines a base rc and additions into single file. Args: base_cfg (ConfigParser.ConfigParser): The configuration we are merging into. target_filename (str): The filename where the new configura...
def run_command(args): """Script entry point. Lints both sets of files.""" library_rc = 'pylintrc' test_rc = 'pylintrc.test' if os.path.exists(library_rc): os.remove(library_rc) if os.path.exists(test_rc): os.remove(test_rc) default_config = read_config(get_default_config()) ...
def u2open(self, u2request): """ Open a connection. @param u2request: A urllib2 request. @type u2request: urllib2.Requet. @return: The opened file-like urllib2 object. @rtype: fp """ tm = self.options.timeout url = build_opener(HTTPSClientAuthHandl...
def login(self, username=None, password=None): """Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type...
def logout(self): """Logout of a vSphere server.""" if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False
def invoke(self, method, _this, **kwargs): """Invoke a method on the server. >>> client.invoke('CurrentTime', client.si) :param method: The method to invoke, as found in the SDK. :type method: str :param _this: The managed object reference against which to invoke \ the ...
def _mor_to_pobject(self, mo_ref): """Converts a MOR to a psphere object.""" kls = classmapper(mo_ref._type) new_object = kls(mo_ref, self) return new_object
def _marshal(self, obj): """Walks an object and marshals any psphere object into MORs.""" logger.debug("Checking if %s needs to be marshalled", obj) if isinstance(obj, ManagedObject): logger.debug("obj is a psphere object, converting to MOR") return obj._mo_ref i...
def _unmarshal(self, obj): """Walks an object and unmarshals any MORs into psphere objects.""" if isinstance(obj, suds.sudsobject.Object) is False: logger.debug("%s is not a suds instance, skipping", obj) return obj logger.debug("Processing:") logger.debug(obj) ...
def create(self, type_, **kwargs): """Create a SOAP object of the requested type. >>> client.create('VirtualE1000') :param type_: The type of SOAP object to create. :type type_: str :param kwargs: TODO :type kwargs: TODO """ obj = self.factory.create("n...
def get_view(self, mo_ref, properties=None): """Get a view of a vSphere managed object. :param mo_ref: The MOR to get a view of :type mo_ref: ManagedObjectReference :param properties: A list of properties to retrieve from the \ server :type properties: list ...
def get_views(self, mo_refs, properties=None): """Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve...
def get_search_filter_spec(self, begin_entity, property_spec): """Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: Th...
def invoke_task(self, method, **kwargs): """Execute a \*_Task method and wait for it to complete. :param method: The \*_Task method to invoke. :type method: str :param kwargs: The arguments to pass to the method. :type kwargs: TODO """ # Don't execute me...
def find_entity_views(self, view_type, begin_entity=None, properties=None): """Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The defaul...
def find_entity_view(self, view_type, begin_entity=None, filter={}, properties=None): """Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_typ...
def load_template(name=None): """Loads a template of the specified name. Templates are placed in the <template_dir> directory in YAML format with a .yaml extension. If no name is specified then the function will return the default template (<template_dir>/default.yaml) if it exists. :para...
def list_templates(): """Returns a list of all templates.""" templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))] return templates
def create_vm(client, name, compute_resource, datastore, disksize, nics, memory, num_cpus, guest_id, host=None): """Create a virtual machine using the specified values. :param name: The name of the VM to create. :type name: str :param compute_resource: The name of a ComputeResource in whi...
def create_nic(client, target, nic): """Return a NIC spec""" # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["network_name"]: net = network break else: return None # Succe...
def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", o...
def add_ignore_patterns(self, *patterns): """ Adds an ignore pattern to the list for ignore patterns. Ignore patterns are used to filter out unwanted files or directories from the file system model. A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a dee...
def set_context_menu(self, context_menu): """ Sets the context menu of the tree view. :param context_menu: QMenu """ self.context_menu = context_menu self.context_menu.tree_view = self self.context_menu.init_actions() for action in self.context_menu.actio...
def set_root_path(self, path, hide_extra_columns=True): """ Sets the root path to watch :param path: root path - str :param hide_extra_columns: Hide extra column (size, paths,...) """ if not self.isVisible(): self._path_to_set = path self._hide_ext...
def filePath(self, index): """ Gets the file path of the item at the specified ``index``. :param index: item index - QModelIndex :return: str """ return self._fs_model_source.filePath( self._fs_model_proxy.mapToSource(index))
def fileInfo(self, index): """ Gets the file info of the item at the specified ``index``. :param index: item index - QModelIndex :return: QFileInfo """ return self._fs_model_source.fileInfo( self._fs_model_proxy.mapToSource(index))
def copy_to_clipboard(self, copy=True): """ Copies the selected items to the clipboard :param copy: True to copy, False to cut. """ urls = self.selected_urls() if not urls: return mime = self._UrlListMimeData(copy) mime.set_list(urls) c...
def selected_urls(self): """ Gets the list of selected items file path (url) """ urls = [] debug('gettings urls') for proxy_index in self.tree_view.selectedIndexes(): finfo = self.tree_view.fileInfo(proxy_index) urls.append(finfo.canonicalFilePath(...
def paste_from_clipboard(self): """ Pastes files from clipboard. """ to = self.get_current_path() if os.path.isfile(to): to = os.path.abspath(os.path.join(to, os.pardir)) mime = QtWidgets.QApplication.clipboard().mimeData() paste_operation = None ...
def _paste(self, sources, destination, copy): """ Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False. """ for src in sources: debug('%s <%s> to <%s>' % ( 'copying' if copy else 'cutting', src, destination)...
def _get_files(path): """ Returns the list of files contained in path (recursively). """ ret_val = [] for root, _, files in os.walk(path): for f in files: ret_val.append(os.path.join(root, f)) return ret_val
def delete(self): """ Deletes the selected items. """ urls = self.selected_urls() rep = QtWidgets.QMessageBox.question( self.tree_view, _('Confirm delete'), _('Are you sure about deleting the selected files/directories?'), QtWidgets.QMessageBox...
def get_current_path(self): """ Gets the path of the currently selected item. """ path = self.tree_view.fileInfo( self.tree_view.currentIndex()).filePath() # https://github.com/pyQode/pyQode/issues/6 if not path: path = self.tree_view.root_path ...
def copy_path_to_clipboard(self): """ Copies the file path to the clipboard """ path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdi...
def create_directory(self): """ Creates a directory under the selected directory (if the selected item is a file, the parent directory is used). """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create director...
def create_file(self): """ Creates a file under the current directory. """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create new file'), _('File name:'), QtWidgets.QLineEdit.Normal, '') if status...
def get_mimetype(path): """ Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type. """ filename = os.path.split(path)[1] mimetype = mimetypes.guess_type(...
def open(self, path, encoding=None, use_cached_encoding=True): """ Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a s...
def reload(self, encoding): """ Reload the file with another encoding. :param encoding: the new encoding to use to reload the file. """ assert os.path.exists(self.path) self.open(self.path, encoding=encoding, use_cached_encoding=False)
def save(self, path=None, encoding=None, fallback_encoding=None): """ Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use th...
def close(self, clear=True): """ Close the file open in the editor: - clear editor content - reset file attributes to their default values :param clear: True to clear the editor content. Default is True. """ Cache().set_cursor_position( self.p...
def on_state_changed(self, state): """ Connects/Disconnects to the painted event of the editor :param state: Enable state """ if state: self.editor.painted.connect(self._paint_margin) self.editor.repaint() else: self.editor.painted.dis...
def _paint_margin(self, event): """ Paints the right margin after editor paint event. """ font = QtGui.QFont(self.editor.font_name, self.editor.font_size + self.editor.zoom_level) metrics = QtGui.QFontMetricsF(font) pos = self._margin_pos offset = self....
def _update_mtime(self): """ Updates modif time """ try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): #...
def _check_file(self): """ Checks watched file moficiation time and permission changes. """ try: self.editor.toPlainText() except RuntimeError: self._timer.stop() return if self.editor and self.editor.file.path: if not os.pa...
def _notify(self, title, message, expected_action=None): """ Notify user from external event """ if self.editor is None: return inital_value = self.editor.save_on_focus_out self.editor.save_on_focus_out = False self._flg_notify = True dlg_type ...
def _notify_change(self): """ Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor """ def inner_action(*args): """ Inner action: open file """ # cache cursor position before reloading so that the c...
def _check_for_pending(self, *args, **kwargs): """ Checks if a notification is pending. """ if self._notification_pending and not self._processing: self._processing = True args, kwargs = self._data self._notify(*args, **kwargs) self._notifi...
def _notify_deleted_file(self): """ Notify user from external file deletion. """ self.file_deleted.emit(self.editor) # file deleted, disable file watcher self.enabled = False
def get_gae_versions(): """Gets a list of all of the available Python SDK versions, sorted with the newest last.""" r = requests.get(SDK_RELEASES_URL) r.raise_for_status() releases = r.json().get('items', {}) # We only care about the Python releases, which all are in the format # "featured...
def is_existing_up_to_date(destination, latest_version): """Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') if not os.path.exists(version_path): ...
def download_sdk(url): """Downloads the SDK and returns a file-like object for the zip content.""" r = requests.get(url) r.raise_for_status() return StringIO(r.content)
def fixup_version(destination, version): """Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') with open(version_path, 'r') as f: version_data = f.read() ...
def download_command(args): """Downloads and extracts the latest App Engine SDK to the given destination.""" latest_two_versions = list(reversed(get_gae_versions()))[:2] zip = None version_number = None for version in latest_two_versions: if is_existing_up_to_date(args.destination, ver...
def preferred_encodings(self): """ The list of user defined encodings, for display in the encodings menu/combobox. """ default_encodings = [ locale.getpreferredencoding().lower().replace('-', '_')] if 'utf_8' not in default_encodings: default_enco...
def get_file_encoding(self, file_path, preferred_encoding=None): """ Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding. ...
def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache """ try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeEr...
def get_cursor_position(self, file_path): """ Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0) """ try: map = json.loads(self._settings.value('cachedCursorPosition')) ...
def set_cursor_position(self, path, position): """ Cache encoding for the specified file path. :param path: path of the file to cache :param position: cursor position to cache """ try: map = json.loads(self._settings.value('cachedCursorPosition')) exc...
def _mid(string, start, end=None): """ Returns a substring delimited by start and end position. """ if end is None: end = len(string) return string[start:start + end]
def _ansi_color(code, theme): """ Converts an ansi code to a QColor, taking the color scheme (theme) into account. """ red = 170 if code & 1 else 0 green = 170 if code & 2 else 0 blue = 170 if code & 4 else 0 color = QtGui.QColor(red, green, blue) if theme is not None: mappings =...
def _qkey_to_ascii(event): """ (Try to) convert the Qt key event to the corresponding ASCII sequence for the terminal. This works fine for standard alphanumerical characters, but most other characters require terminal specific control_modifier sequences. The conversion below works for TERM="linux' t...
def is_running(self): """ Checks if the child process is running (or is starting). """ return self._process.state() in [self._process.Running, self._process.Starting]
def start_process(self, program, arguments=None, working_dir=None, print_command=True, use_pseudo_terminal=True, env=None): """ Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: workin...
def stop_process(self): """ Stops the child process. """ self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
def create_color_scheme(background=None, foreground=None, error=None, custom=None, red=None, green=None, yellow=None, blue=None, magenta=None, cyan=None): """ Utility function that creates a color scheme instance, with default values. The default colors are chosen ba...
def closeEvent(self, event): """ Terminates the child process on close. """ self.stop_process() self.backend.stop() try: self.modes.remove('_LinkHighlighter') except KeyError: pass # already removed super(OutputWindow, self).closeE...
def keyPressEvent(self, event): """ Handle key press event using the defined input handler. """ if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setP...
def mouseMoveEvent(self, event): """ Handle mouse over file link. """ c = self.cursorForPosition(event.pos()) block = c.block() self._link_match = None self.viewport().setCursor(QtCore.Qt.IBeamCursor) for match in self.link_regex.finditer(block.text()): ...
def mousePressEvent(self, event): """ Handle file link clicks. """ super(OutputWindow, self).mousePressEvent(event) if self._link_match: path = self._link_match.group('url') line = self._link_match.group('line') if line is not None: ...
def _init_code_edit(self, backend): """ Initializes the code editor (setup modes, panels and colors). """ from pyqode.core import panels, modes self.modes.append(_LinkHighlighter(self.document())) self.background = self._formatter.color_scheme.background self.fore...
def _setup_process_environment(self, env): """ Sets up the process environment. """ environ = self._process.processEnvironment() if env is None: env = {} for k, v in os.environ.items(): environ.insert(k, v) for k, v in env.items(): ...
def _on_process_error(self, error): """ Display child process error in the text edit. """ if self is None: return err = PROCESS_ERROR_STRING[error] self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat)
def _on_process_finished(self): """ Write the process finished message and emit the `finished` signal. """ exit_code = self._process.exitCode() if self._process.exitStatus() != self._process.NormalExit: exit_code = 139 self._formatter.append_message('\x1b[0m\n...
def _read_stdout(self): """ Reads the child process' stdout and process it. """ output = self._decode(self._process.readAllStandardOutput().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.NormalMessageFormat) else:...
def _read_stderr(self): """ Reads the child process' stderr and process it. """ output = self._decode(self._process.readAllStandardError().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.ErrorMessageFormat) else: ...
def parse_text(self, formatted_text): """ Retursn a list of operations (draw, cup, ed,...). Each operation consist of a command and its associated data. :param formatted_text: text to parse with the default char format to apply. :return: list of Operation """ as...
def _set_format_scope(self, fmt): """ Opens the format scope. """ self._prev_fmt = QtGui.QTextCharFormat(fmt) self._prev_fmt_closed = False
def key_press_event(self, event): """ Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event from being propagated to the parent widget. """ if event.key() == QtCore.Qt.Key_Return: cursor = self.edit.textCursor() ...
def add_command(self, command): """ Adds a command to the history and reset history index. """ try: self._history.remove(command) except ValueError: pass self._history.insert(0, command) self._index = -1
def scroll_up(self): """ Returns the previous command, if any. """ self._index += 1 nb_commands = len(self._history) if self._index >= nb_commands: self._index = nb_commands - 1 try: return self._history[self._index] except IndexErr...
def scroll_down(self): """ Returns the next command if any. """ self._index -= 1 if self._index < 0: self._index = -1 return '' try: return self._history[self._index] except IndexError: return ''
def _insert_command(self, command): """ Insert command by replacing the current input buffer and display it on the text edit. """ self._clear_user_buffer() tc = self.edit.textCursor() tc.insertText(command) self.edit.setTextCursor(tc)
def key_press_event(self, event): """ Manages our own buffer and send it to the subprocess when user pressed RETURN. """ input_buffer = self._get_input_buffer() ctrl = int(event.modifiers() & QtCore.Qt.ControlModifier) != 0 shift = int(event.modifiers() & QtCore.Qt.ShiftM...
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat): """ Parses and append message to the text edit. """ self._append_message(text, self._formats[output_format])
def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try:...
def _init_formats(self): """ Initialise default formats. """ theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalM...
def _draw(self, data): """ Draw text """ self._cursor.clearSelection() self._cursor.setPosition(self._last_cursor_pos) if '\x07' in data.txt: print('\a') txt = data.txt.replace('\x07', '') if '\x08' in txt: parts = txt.split('\x08...
def _draw_chars(self, data, to_draw): """ Draw the specified charachters using the specified format. """ i = 0 while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1: self._cursor.deleteChar() i += 1 self._cursor.insertText(t...
def _linefeed(self): """ Performs a line feed. """ last_line = self._cursor.blockNumber() == self._text_edit.blockCount() - 1 if self._cursor.atEnd() or last_line: if last_line: self._cursor.movePosition(self._cursor.EndOfBlock) self._curso...
def _cursor_down(self, value): """ Moves the cursor down by ``value``. """ self._cursor.clearSelection() if self._cursor.atEnd(): self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, value) ...
def _cursor_up(self, value): """ Moves the cursor up by ``value``. """ value = int(value) if value == 0: value = 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.Up, self._cursor.MoveAnchor, value) self._last_cursor_pos = ...
def _cursor_position(self, data): """ Moves the cursor position. """ column, line = self._get_line_and_col(data) self._move_cursor_to_line(line) self._move_cursor_to_column(column) self._last_cursor_pos = self._cursor.position()
def _move_cursor_to_column(self, column): """ Moves the cursor to the specified column, if possible. """ last_col = len(self._cursor.block().text()) self._cursor.movePosition(self._cursor.EndOfBlock) to_insert = '' for i in range(column - last_col): to...
def _move_cursor_to_line(self, line): """ Moves the cursor to the specified line, if possible. """ last_line = self._text_edit.document().blockCount() - 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.End) to_insert = '' for i in ran...
def _get_line_and_col(data): """ Gets line and column from a string like the following: "1;5" or "1;" or ";5" and convers the column/line numbers to 0 base. """ try: line, column = data.split(';') except AttributeError: line = int(data) ...
def _erase_in_line(self, value): """ Erases charachters in line. """ initial_pos = self._cursor.position() if value == 0: # delete end of line self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) elif value == 1: ...
def _erase_display(self, value): """ Erases display. """ if value == 0: # delete end of line self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self...