text
stringlengths
81
112k
Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up. 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, ...
Downloads and extracts the latest App Engine SDK to the given destination. 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...
The list of user defined encodings, for display in the encodings menu/combobox. def preferred_encodings(self): """ The list of user defined encodings, for display in the encodings menu/combobox. """ default_encodings = [ locale.getpreferredencoding().lower()...
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 get_file_encoding(self, file_path, preferred_encoding=None): """ G...
Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: en...
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) 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 ...
Cache encoding for the specified file path. :param path: path of the file to cache :param position: cursor position to cache def set_cursor_position(self, path, position): """ Cache encoding for the specified file path. :param path: path of the file to cache :param pos...
Returns a substring delimited by start and end position. 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]
Converts an ansi code to a QColor, taking the color scheme (theme) into account. 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 c...
(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' terminals. def _qkey_to_ascii(event): ...
Checks if the child process is running (or is starting). 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]
Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window ...
Stops the child process. def stop_process(self): """ Stops the child process. """ self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of...
Terminates the child process on close. 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 ...
Handle key press event using the defined input handler. 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.selectionSt...
Handle mouse over file link. 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_re...
Handle file link clicks. 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 lin...
Initializes the code editor (setup modes, panels and colors). 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.backgro...
Sets up the process environment. 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) ...
Display child process error in the text edit. 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=Output...
Write the process finished message and emit the `finished` signal. 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: ...
Reads the child process' stdout and process it. 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_forma...
Reads the child process' stderr and process it. 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...
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 def parse_text(self, formatted_text): """ Retursn a list of ope...
Opens the format scope. def _set_format_scope(self, fmt): """ Opens the format scope. """ self._prev_fmt = QtGui.QTextCharFormat(fmt) self._prev_fmt_closed = False
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. def key_press_event(self, event): """ Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event f...
Adds a command to the history and reset history index. 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) ...
Returns the previous command, if any. 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._histo...
Returns the next command if any. 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: ...
Insert command by replacing the current input buffer and display it on the text edit. 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() t...
Manages our own buffer and send it to the subprocess when user pressed RETURN. 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.Q...
Parses and append message to the text edit. 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])
Parses text and executes parsed operations. 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, operati...
Initialise default formats. 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....
Draw text 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....
Draw the specified charachters using the specified format. 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.delet...
Performs a line feed. 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) ...
Moves the cursor down by ``value``. 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, ...
Moves the cursor up by ``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, valu...
Moves the cursor position. 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()
Moves the cursor to the specified column, if possible. 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 = '' ...
Moves the cursor to the specified line, if possible. 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._c...
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. 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. ...
Erases charachters in line. 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) ...
Erases display. 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....
Moves the cursor back. def _cursor_back(self, value): """ Moves the cursor back. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Left, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_po...
Moves the cursor forward. def _cursor_forward(self, value): """ Moves the cursor forward. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last...
Deletes the specified number of charachters. def _delete_chars(self, value): """ Deletes the specified number of charachters. """ value = int(value) if value <= 0: value = 1 for i in range(value): self._cursor.deleteChar() self._text_edit....
Gets the PyPI information for a given package. def get_package_info(package): """Gets the PyPI information for a given package.""" url = 'https://pypi.python.org/pypi/{}/json'.format(package) r = requests.get(url) r.raise_for_status() return r.json()
Reads a requirements file. Args: req_file (str): Filename of requirements file def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for ite...
Returns true if requirements specify a version range. def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' ...
Updates a given req object with the latest version. def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be upda...
Writes a list of req objects out to a given file. def write_requirements(reqs_linenum, req_file): """Writes a list of req objects out to a given file.""" with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0],...
Checks if a given req is the latest version available. def check_req(req): """Checks if a given req is the latest version available.""" if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_...
Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore. def check_requirements_file(req_file, skip_packages): """Return list of outdated requirements. Args: req_file (str): Filename of require...
Updates all dependencies the specified requirements file. def update_command(args): """Updates all dependencies the specified requirements file.""" updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.re...
Checks that all dependencies in the specified requirements file are up to date. def check_command(args): """Checks that all dependencies in the specified requirements file are up to date.""" outdated = check_requirements_file(args.requirements_file, args.skip_pack...
Fills the panel background. def paintEvent(self, event): """ Fills the panel background. """ super(EncodingPanel, self).paintEvent(event) if self.isVisible(): # fill background painter = QtGui.QPainter(self) self._background_brush = QtGui.QBrush(self._color) ...
Returns a QTextCharFormat for token by reading a Pygments style. def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, ...
Returns a QColor built from a Pygments color string. def _get_color(color): """ Returns a QColor built from a Pygments color string. """ color = str(color).replace("#", "") qcolor = QtGui.QColor() qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16), ...
Refresh editor settings (background and highlight colors) when color scheme changed. :param color_scheme: new color scheme. def refresh_editor(self, color_scheme): """ Refresh editor settings (background and highlight colors) when color scheme changed. :param color_sch...
Rehighlight the entire document, may be slow. def rehighlight(self): """ Rehighlight the entire document, may be slow. """ start = time.time() QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) try: super(SyntaxHighligh...
Computes the lineNumber area width depending on the number of lines in the document :return: Widtg def line_number_area_width(self): """ Computes the lineNumber area width depending on the number of lines in the document :return: Widtg """ digits = 1 ...
Starts selecting def mousePressEvent(self, e): """ Starts selecting """ self._selecting = True self._sel_start = e.pos().y() start = end = TextHelper(self.editor).line_nbr_from_position( self._sel_start) self._start_line = start TextHelper(sel...
Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit def set_editor(self, editor): """ Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit """ try: se...
Update the tree items def _on_changed(self): """ Update the tree items """ self._updating = True to_collapse = [] self.clear() if self._editor and self._outline_mode and self._folding_panel: items, to_collapse = self.to_tree_widget_items( ...
Go to the item position in the editor. def _on_item_clicked(self, item): """ Go to the item position in the editor. """ if item: name = item.data(0, QtCore.Qt.UserRole) if name: go = name.block.blockNumber() helper = TextHelper(sel...
Converts the list of top level definitions to a list of top level tree items. def to_tree_widget_items(self, definitions, to_collapse=None): """ Converts the list of top level definitions to a list of top level tree items. """ def flatten(definitions): """ ...
Find the corresponding symbol position (line, column) of the specified symbol. If symbol type is PAREN and character_type is OPEN, the function will look for '('. :param cursor: QTextCursor :param character_type: character type to look for (open or close char) :param symbol_type...
Performs symbols matching. def do_symbols_matching(self): """ Performs symbols matching. """ self._clear_decorations() current_block = self.editor.textCursor().block() data = get_block_symbol_data(self.editor, current_block) pos = self.editor.textCursor().block()...
Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden). def set_button_visible(self, visible): """ Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden). """ self.button.setVisib...
Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class def import_class(klass): """ Imports a class from a fully qualified name string. :param klass: class string, e.g. ...
Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. def serve_forever(args=None): """ Creates the server and serves forever :param ...
Create associated actions def _create_actions(self): """ Create associated actions """ self.action_to_lower = QtWidgets.QAction(self.editor) self.action_to_lower.triggered.connect(self.to_lower) self.action_to_upper = QtWidgets.QAction(self.editor) self.action_to_upper.triggered...
Selects the word under the mouse cursor. def _select_word_cursor(self): """ Selects the word under the mouse cursor. """ cursor = TextHelper(self.editor).word_under_mouse_cursor() if (self._previous_cursor_start != cursor.selectionStart() and self._previous_cursor_end != cursor....
mouse moved callback def _on_mouse_moved(self, event): """ mouse moved callback """ if event.modifiers() & QtCore.Qt.ControlModifier: cursor = TextHelper(self.editor).word_under_mouse_cursor() if (not self._cursor or cursor.position() != self._cursor.position...
mouse pressed callback def _on_mouse_released(self, event): """ mouse pressed callback """ if event.button() == 1 and self._deco: cursor = TextHelper(self.editor).word_under_mouse_cursor() if cursor and cursor.selectedText(): self._timer.request_job( ...
Adds a decoration for the word under ``cursor``. def _add_decoration(self, cursor): """ Adds a decoration for the word under ``cursor``. """ if self._deco is None: if cursor.selectedText(): self._deco = TextDecoration(cursor) if self.editor.ba...
Removes the word under cursor's decoration def _remove_decoration(self): """ Removes the word under cursor's decoration """ if self._deco is not None: self.editor.decorations.remove(self._deco) self._deco = None
DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime`` type and the format changes between DokuWiki versions ... This function convert *date* to a `datetime` object. def date(date): """DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime`` type and the format changes between Dok...
DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time. def utc2local(date): """DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time. """ date_offset = (datetime.now() - datetime.utcnow()) # Python < 2.7 don't have the ...
parse and store cookie def parse_response(self, response): """parse and store cookie""" try: for header in response.msg.get_all("Set-Cookie"): cookie = header.split(";", 1)[0] cookieKey, cookieValue = cookie.split("=", 1) self._cookies[cookieK...
parse and store cookie def parse_response(self, response): """parse and store cookie""" try: for header in response.getheader("set-cookie").split(", "): # filter 'expire' information if not header.startswith("D"): continue ...
Generic method for executing an XML-RPC *command*. *args* and *kwargs* are the arguments and parameters needed by the command. def send(self, command, *args, **kwargs): """Generic method for executing an XML-RPC *command*. *args* and *kwargs* are the arguments and parameters needed by the comma...
Add an `ACL <https://www.dokuwiki.org/acl>`_ rule that restricts the page/namespace *scope* to *user* (use *@group* syntax for groups) with *permission* level. It returns a boolean that indicate if the rule was correctly added. def add_acl(self, scope, user, permission): """Add an `ACL ...
Returns informations of *page*. Informations of the last version is returned if *version* is not set. def info(self, page, version=None): """Returns informations of *page*. Informations of the last version is returned if *version* is not set. """ return (self._dokuwiki.send('wik...
Returns the content of *page*. The content of the last version is returned if *version* is not set. def get(self, page, version=None): """Returns the content of *page*. The content of the last version is returned if *version* is not set. """ return (self._dokuwiki.send('wiki.get...
Appends *content* text to *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change def append(self, page, content, **options): """Appends *content* text to *page*. Valid *options* are: * *sum*: (str) chan...
Returns HTML content of *page*. The HTML content of the last version of the page is returned if *version* is not set. def html(self, page, version=None): """Returns HTML content of *page*. The HTML content of the last version of the page is returned if *version* is not set. """ ...
Set/replace the *content* of *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change def set(self, page, content, **options): """Set/replace the *content* of *page*. Valid *options* are: * *sum*: (str) c...
Locks *page*. def lock(self, page): """Locks *page*.""" result = self._dokuwiki.send('dokuwiki.setLocks', lock=[page], unlock=[]) if result['lockfail']: raise DokuWikiError('unable to lock page')
Returns the binary data of *media* or save it to a file. If *dirpath* is not set the binary data is returned, otherwise the data is saved to a file. By default, the filename is the name of the media but it can be changed with *filename* parameter. *overwrite* parameter allow to overwrite...
Set *media* from local file *filepath*. *overwrite* parameter specify if the media must be overwrite if it exists remotely. def add(self, media, filepath, overwrite=True): """Set *media* from local file *filepath*. *overwrite* parameter specify if the media must be overwrite if it exists remote...
Set *media* from *_bytes*. *overwrite* parameter specify if the media must be overwrite if it exists remotely. def set(self, media, _bytes, overwrite=True, b64encode=False): """Set *media* from *_bytes*. *overwrite* parameter specify if the media must be overwrite if it exists remotely. ...
Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay. def get(content, keep_order=False): """Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay.""" if keep_order: from collections import Ordere...
Generate dataentry *name* from *data*. def gen(name, data): """Generate dataentry *name* from *data*.""" return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join( '%s:%s' % (attr, value) for attr, value in data.items()))
Remove dataentry from *content*. def ignore(content): """Remove dataentry from *content*.""" page_content = [] start = False for line in content.split('\n'): if line == '----' and not start: start = True continue if start: ...
Draw messages from all subclass of CheckerMode currently installed on the editor. :type painter: QtGui.QPainter def _draw_messages(self, painter): """ Draw messages from all subclass of CheckerMode currently installed on the editor. :type painter: QtGui.QPainter ...
Draw the visible area. This method does not take folded blocks into account. :type painter: QtGui.QPainter def _draw_visible_area(self, painter): """ Draw the visible area. This method does not take folded blocks into account. :type painter: QtGui.QPainter ""...