_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q3300
Indenter.onChangeSelectedBlocksIndent
train
def onChangeSelectedBlocksIndent(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if(cursor.selectionStart() != cursor.selectionEnd() and endBlock.position() == cursor.selectionEnd() and endBlock.previous().isValid()): endBlock = endBlock.previous() # do not indent not selected line if indenting multiple lines indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock)
python
{ "resource": "" }
q3301
Indenter.onShortcutIndentAfterCursor
train
def onShortcutIndentAfterCursor(self): """Tab pressed and no selection. Insert text after cursor """ cursor = self._qpart.textCursor() def insertIndent(): if self.useTabs: cursor.insertText('\t') else: # indent to integer count of indents from line start charsToInsert = self.width - (len(self._qpart.textBeforeCursor()) % self.width) cursor.insertText(' ' * charsToInsert) if cursor.positionInBlock() == 0: # if no any indent - indent smartly block = cursor.block() self.autoIndentBlock(block, '') # if no smart indentation - just insert one indent if self._qpart.textBeforeCursor() == '': insertIndent() else: insertIndent()
python
{ "resource": "" }
q3302
Indenter.onShortcutUnindentWithBackspace
train
def onShortcutUnindentWithBackspace(self): """Backspace pressed, unindent """ assert self._qpart.textBeforeCursor().endswith(self.text()) charsToRemove = len(self._qpart.textBeforeCursor()) % len(self.text()) if charsToRemove == 0: charsToRemove = len(self.text()) cursor = self._qpart.textCursor() cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText()
python
{ "resource": "" }
q3303
Indenter.onAutoIndentTriggered
train
def onAutoIndentTriggered(self): """Indent current line or selected lines """ cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: self.autoIndentBlock(block, '') block = block.next() else: # indent 1 line self.autoIndentBlock(startBlock, '')
python
{ "resource": "" }
q3304
Indenter._chooseSmartIndenter
train
def _chooseSmartIndenter(self, syntax): """Get indenter for syntax """ if syntax.indenter is not None: try: return _getSmartIndenter(syntax.indenter, self._qpart, self) except KeyError: logger.error("Indenter '%s' is not finished yet. But you can do it!" % syntax.indenter) try: return _getSmartIndenter(syntax.name, self._qpart, self) except KeyError: pass return _getSmartIndenter('normal', self._qpart, self)
python
{ "resource": "" }
q3305
_processEscapeSequences
train
def _processEscapeSequences(replaceText): """Replace symbols like \n \\, etc """ def _replaceFunc(escapeMatchObject): char = escapeMatchObject.group(0)[1] if char in _escapeSequences: return _escapeSequences[char] return escapeMatchObject.group(0) # no any replacements, return original value return _seqReplacer.sub(_replaceFunc, replaceText)
python
{ "resource": "" }
q3306
_loadChildRules
train
def _loadChildRules(context, xmlElement, attributeToFormatMap): """Extract rules from Context or Rule xml element """ rules = [] for ruleElement in xmlElement.getchildren(): if not ruleElement.tag in _ruleClassDict: raise ValueError("Not supported rule '%s'" % ruleElement.tag) rule = _ruleClassDict[ruleElement.tag](context, ruleElement, attributeToFormatMap) rules.append(rule) return rules
python
{ "resource": "" }
q3307
_loadContext
train
def _loadContext(context, xmlElement, attributeToFormatMap): """Construct context from XML element Contexts are at first constructed, and only then loaded, because when loading context, _makeContextSwitcher must have references to all defined contexts """ attribute = _safeGetRequiredAttribute(xmlElement, 'attribute', '<not set>').lower() if attribute != '<not set>': # there are no attributes for internal contexts, used by rules. See perl.xml try: format = attributeToFormatMap[attribute] except KeyError: _logger.warning('Unknown context attribute %s', attribute) format = TextFormat() else: format = None textType = format.textType if format is not None else ' ' if format is not None: format = _convertFormat(format) lineEndContextText = xmlElement.attrib.get('lineEndContext', '#stay') lineEndContext = _makeContextSwitcher(lineEndContextText, context.parser) lineBeginContextText = xmlElement.attrib.get('lineBeginContext', '#stay') lineBeginContext = _makeContextSwitcher(lineBeginContextText, context.parser) lineEmptyContextText = xmlElement.attrib.get('lineEmptyContext', '#stay') lineEmptyContext = _makeContextSwitcher(lineEmptyContextText, context.parser) if _parseBoolAttribute(xmlElement.attrib.get('fallthrough', 'false')): fallthroughContextText = _safeGetRequiredAttribute(xmlElement, 'fallthroughContext', '#stay') fallthroughContext = _makeContextSwitcher(fallthroughContextText, context.parser) else: fallthroughContext = None dynamic = _parseBoolAttribute(xmlElement.attrib.get('dynamic', 'false')) context.setValues(attribute, format, lineEndContext, lineBeginContext, lineEmptyContext, fallthroughContext, dynamic, textType) # load rules rules = _loadChildRules(context, xmlElement, attributeToFormatMap) context.setRules(rules)
python
{ "resource": "" }
q3308
_textTypeForDefStyleName
train
def _textTypeForDefStyleName(attribute, defStyleName): """ ' ' for code 'c' for comments 'b' for block comments 'h' for here documents """ if 'here' in attribute.lower() and defStyleName == 'dsOthers': return 'h' # ruby elif 'block' in attribute.lower() and defStyleName == 'dsComment': return 'b' elif defStyleName in ('dsString', 'dsRegionMarker', 'dsChar', 'dsOthers'): return 's' elif defStyleName == 'dsComment': return 'c' else: return ' '
python
{ "resource": "" }
q3309
IndentAlgBase.computeIndent
train
def computeIndent(self, block, char): """Compute indent for the block. Basic alorightm, which knows nothing about programming languages May be used by child classes """ prevBlockText = block.previous().text() # invalid block returns empty text if char == '\n' and \ prevBlockText.strip() == '': # continue indentation, if no text return self._prevBlockIndent(block) else: # be smart return self.computeSmartIndent(block, char)
python
{ "resource": "" }
q3310
IndentAlgBase._decreaseIndent
train
def _decreaseIndent(self, indent): """Remove 1 indentation level """ if indent.endswith(self._qpartIndent()): return indent[:-len(self._qpartIndent())] else: # oops, strange indentation, just return previous indent return indent
python
{ "resource": "" }
q3311
IndentAlgBase._makeIndentFromWidth
train
def _makeIndentFromWidth(self, width): """Make indent text with specified with. Contains width count of spaces, or tabs and spaces """ if self._indenter.useTabs: tabCount, spaceCount = divmod(width, self._indenter.width) return ('\t' * tabCount) + (' ' * spaceCount) else: return ' ' * width
python
{ "resource": "" }
q3312
IndentAlgBase._makeIndentAsColumn
train
def _makeIndentAsColumn(self, block, column, offset=0): """ Make indent equal to column indent. Shiftted by offset """ blockText = block.text() textBeforeColumn = blockText[:column] tabCount = textBeforeColumn.count('\t') visibleColumn = column + (tabCount * (self._indenter.width - 1)) return self._makeIndentFromWidth(visibleColumn + offset)
python
{ "resource": "" }
q3313
IndentAlgBase._setBlockIndent
train
def _setBlockIndent(self, block, indent): """Set blocks indent. Modify text in qpart """ currentIndent = self._blockIndent(block) self._qpart.replaceText((block.blockNumber(), 0), len(currentIndent), indent)
python
{ "resource": "" }
q3314
IndentAlgBase.iterateBlocksFrom
train
def iterateBlocksFrom(block): """Generator, which iterates QTextBlocks from block until the End of a document But, yields not more than MAX_SEARCH_OFFSET_LINES """ count = 0 while block.isValid() and count < MAX_SEARCH_OFFSET_LINES: yield block block = block.next() count += 1
python
{ "resource": "" }
q3315
IndentAlgBase.iterateBlocksBackFrom
train
def iterateBlocksBackFrom(block): """Generator, which iterates QTextBlocks from block until the Start of a document But, yields not more than MAX_SEARCH_OFFSET_LINES """ count = 0 while block.isValid() and count < MAX_SEARCH_OFFSET_LINES: yield block block = block.previous() count += 1
python
{ "resource": "" }
q3316
IndentAlgBase._lastColumn
train
def _lastColumn(self, block): """Returns the last non-whitespace column in the given line. If there are only whitespaces in the line, the return value is -1. """ text = block.text() index = len(block.text()) - 1 while index >= 0 and \ (text[index].isspace() or \ self._qpart.isComment(block.blockNumber(), index)): index -= 1 return index
python
{ "resource": "" }
q3317
IndentAlgBase._nextNonSpaceColumn
train
def _nextNonSpaceColumn(block, column): """Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards. """ textAfter = block.text()[column:] if textAfter.strip(): spaceLen = len(textAfter) - len(textAfter.lstrip()) return column + spaceLen else: return -1
python
{ "resource": "" }
q3318
_checkBuildDependencies
train
def _checkBuildDependencies(): compiler = distutils.ccompiler.new_compiler() """check if function without parameters from stdlib can be called There should be better way to check, if C compiler is installed """ if not compiler.has_function('rand', includes=['stdlib.h']): print("It seems like C compiler is not installed or not operable.") return False if not compiler.has_function('rand', includes=['stdlib.h', 'Python.h'], include_dirs=[distutils.sysconfig.get_python_inc()], library_dirs=[os.path.join(os.path.dirname(sys.executable), 'libs')]): print("Failed to find Python headers.") print("Try to install python-dev package") print("If not standard directories are used, pass parameters") print("\tpython setup.py install --lib-dir=c://github/pcre-8.37/build/Release --include-dir=c://github/pcre-8.37/build") print("\tpython setup.py install --lib-dir=/my/local/lib --include-dir=/my/local/include") print("--lib-dir= and --include-dir= may be used multiple times") return False if not compiler.has_function('pcre_version', includes=['pcre.h'], libraries=['pcre'], include_dirs=include_dirs, library_dirs=library_dirs): print("Failed to find pcre library.") print("Try to install libpcre{version}-dev package, or go to http://pcre.org") print("If not standard directories are used, pass parameters:") print("\tpython setup.py install --lib-dir=c://github/pcre-8.37/build/Release --include-dir=c://github/pcre-8.37/build") print("\tpython setup.py install --lib-dir=/my/local/lib --include-dir=/my/local/include") print("--lib-dir= and --include-dir= may be used multiple times") return False return True
python
{ "resource": "" }
q3319
isChar
train
def isChar(ev): """ Check if an event may be a typed character """ text = ev.text() if len(text) != 1: return False if ev.modifiers() not in (Qt.ShiftModifier, Qt.KeypadModifier, Qt.NoModifier): return False asciiCode = ord(text) if asciiCode <= 31 or asciiCode == 0x7f: # control characters return False if text == ' ' and ev.modifiers() == Qt.ShiftModifier: return False # Shift+Space is a shortcut, not a text return True
python
{ "resource": "" }
q3320
Vim.keyPressEvent
train
def keyPressEvent(self, ev): """Check the event. Return True if processed and False otherwise """ if ev.key() in (Qt.Key_Shift, Qt.Key_Control, Qt.Key_Meta, Qt.Key_Alt, Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock): return False # ignore modifier pressing. Will process key pressing later self._processingKeyPress = True try: ret = self._mode.keyPressEvent(ev) finally: self._processingKeyPress = False return ret
python
{ "resource": "" }
q3321
Vim.extraSelections
train
def extraSelections(self): """ In normal mode - QTextEdit.ExtraSelection which highlightes the cursor """ if not isinstance(self._mode, Normal): return [] selection = QTextEdit.ExtraSelection() selection.format.setBackground(QColor('#ffcc22')) selection.format.setForeground(QColor('#000000')) selection.cursor = self._qpart.textCursor() selection.cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return [selection]
python
{ "resource": "" }
q3322
BaseCommandMode._resetSelection
train
def _resetSelection(self, moveToTop=False): """ Reset selection. If moveToTop is True - move cursor to the top position """ ancor, pos = self._qpart.selectedPosition dst = min(ancor, pos) if moveToTop else pos self._qpart.cursorPosition = dst
python
{ "resource": "" }
q3323
BaseVisual._selectedLinesRange
train
def _selectedLinesRange(self): """ Selected lines range for line manipulation methods """ (startLine, startCol), (endLine, endCol) = self._qpart.selectedPosition start = min(startLine, endLine) end = max(startLine, endLine) return start, end
python
{ "resource": "" }
q3324
Normal._repeat
train
def _repeat(self, count, func): """ Repeat action 1 or more times. If more than one - do it as 1 undoble action """ if count != 1: with self._qpart: for _ in range(count): func() else: func()
python
{ "resource": "" }
q3325
Normal.cmdDeleteUntilEndOfBlock
train
def cmdDeleteUntilEndOfBlock(self, cmd, count): """ C and D """ cursor = self._qpart.textCursor() for _ in range(count - 1): cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) _globalClipboard.value = cursor.selectedText() cursor.removeSelectedText() if cmd == _C: self.switchMode(Insert) self._saveLastEditSimpleCmd(cmd, count)
python
{ "resource": "" }
q3326
Qutepart.terminate
train
def terminate(self): """ Terminate Qutepart instance. This method MUST be called before application stop to avoid crashes and some other interesting effects Call it on close to free memory and stop background highlighting """ self.text = '' self._completer.terminate() if self._highlighter is not None: self._highlighter.terminate() if self._vim is not None: self._vim.terminate()
python
{ "resource": "" }
q3327
Qutepart._initActions
train
def _initActions(self): """Init shortcuts for text editing """ def createAction(text, shortcut, slot, iconFileName=None): """Create QAction with given parameters and add to the widget """ action = QAction(text, self) if iconFileName is not None: action.setIcon(getIcon(iconFileName)) keySeq = shortcut if isinstance(shortcut, QKeySequence) else QKeySequence(shortcut) action.setShortcut(keySeq) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) self.addAction(action) return action # scrolling self.scrollUpAction = createAction('Scroll up', 'Ctrl+Up', lambda: self._onShortcutScroll(down = False), 'go-up') self.scrollDownAction = createAction('Scroll down', 'Ctrl+Down', lambda: self._onShortcutScroll(down = True), 'go-down') self.selectAndScrollUpAction = createAction('Select and scroll Up', 'Ctrl+Shift+Up', lambda: self._onShortcutSelectAndScroll(down = False)) self.selectAndScrollDownAction = createAction('Select and scroll Down', 'Ctrl+Shift+Down', lambda: self._onShortcutSelectAndScroll(down = True)) # indentation self.increaseIndentAction = createAction('Increase indentation', 'Tab', self._onShortcutIndent, 'format-indent-more') self.decreaseIndentAction = createAction('Decrease indentation', 'Shift+Tab', lambda: self._indenter.onChangeSelectedBlocksIndent(increase = False), 'format-indent-less') self.autoIndentLineAction = createAction('Autoindent line', 'Ctrl+I', self._indenter.onAutoIndentTriggered) self.indentWithSpaceAction = createAction('Indent with 1 space', 'Ctrl+Shift+Space', lambda: self._indenter.onChangeSelectedBlocksIndent(increase=True, withSpace=True)) self.unIndentWithSpaceAction = createAction('Unindent with 1 space', 'Ctrl+Shift+Backspace', lambda: self._indenter.onChangeSelectedBlocksIndent(increase=False, withSpace=True)) # editing self.undoAction = createAction('Undo', QKeySequence.Undo, self.undo, 'edit-undo') self.redoAction = createAction('Redo', QKeySequence.Redo, self.redo, 'edit-redo') self.moveLineUpAction = createAction('Move line up', 'Alt+Up', lambda: self._onShortcutMoveLine(down = False), 'go-up') self.moveLineDownAction = createAction('Move line down', 'Alt+Down', lambda: self._onShortcutMoveLine(down = True), 'go-down') self.deleteLineAction = createAction('Delete line', 'Alt+Del', self._onShortcutDeleteLine, 'edit-delete') self.cutLineAction = createAction('Cut line', 'Alt+X', self._onShortcutCutLine, 'edit-cut') self.copyLineAction = createAction('Copy line', 'Alt+C', self._onShortcutCopyLine, 'edit-copy') self.pasteLineAction = createAction('Paste line', 'Alt+V', self._onShortcutPasteLine, 'edit-paste') self.duplicateLineAction = createAction('Duplicate line', 'Alt+D', self._onShortcutDuplicateLine) self.invokeCompletionAction = createAction('Invoke completion', 'Ctrl+Space', self._completer.invokeCompletion) # other self.printAction = createAction('Print', 'Ctrl+P', self._onShortcutPrint, 'document-print')
python
{ "resource": "" }
q3328
Qutepart._updateTabStopWidth
train
def _updateTabStopWidth(self): """Update tabstop width after font or indentation changed """ self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width))
python
{ "resource": "" }
q3329
Qutepart.textForSaving
train
def textForSaving(self): """Get text with correct EOL symbols. Use this method for saving a file to storage """ lines = self.text.splitlines() if self.text.endswith('\n'): # splitlines ignores last \n lines.append('') return self.eol.join(lines) + self.eol
python
{ "resource": "" }
q3330
Qutepart.resetSelection
train
def resetSelection(self): """Reset selection. Nothing will be selected. """ cursor = self.textCursor() cursor.setPosition(cursor.position()) self.setTextCursor(cursor)
python
{ "resource": "" }
q3331
Qutepart.replaceText
train
def replaceText(self, pos, length, text): """Replace length symbols from ``pos`` with new text. If ``pos`` is an integer, it is interpreted as absolute position, if a tuple - as ``(line, column)`` """ if isinstance(pos, tuple): pos = self.mapToAbsPosition(*pos) endPos = pos + length if not self.document().findBlock(pos).isValid(): raise IndexError('Invalid start position %d' % pos) if not self.document().findBlock(endPos).isValid(): raise IndexError('Invalid end position %d' % endPos) cursor = QTextCursor(self.document()) cursor.setPosition(pos) cursor.setPosition(endPos, QTextCursor.KeepAnchor) cursor.insertText(text)
python
{ "resource": "" }
q3332
Qutepart.clearSyntax
train
def clearSyntax(self): """Clear syntax. Disables syntax highlighting This method might take long time, if document is big. Don't call it if you don't have to (i.e. in destructor) """ if self._highlighter is not None: self._highlighter.terminate() self._highlighter = None self.languageChanged.emit(None)
python
{ "resource": "" }
q3333
Qutepart.setCustomCompletions
train
def setCustomCompletions(self, wordSet): """Add a set of custom completions to the editors completions. This set is managed independently of the set of keywords and words from the current document, and can thus be changed at any time. """ if not isinstance(wordSet, set): raise TypeError('"wordSet" is not a set: %s' % type(wordSet)) self._completer.setCustomCompletions(wordSet)
python
{ "resource": "" }
q3334
Qutepart.isCode
train
def isCode(self, blockOrBlockNumber, column): """Check if text at given position is a code. If language is not known, or text is not parsed yet, ``True`` is returned """ if isinstance(blockOrBlockNumber, QTextBlock): block = blockOrBlockNumber else: block = self.document().findBlockByNumber(blockOrBlockNumber) return self._highlighter is None or \ self._highlighter.isCode(block, column)
python
{ "resource": "" }
q3335
Qutepart.isComment
train
def isComment(self, line, column): """Check if text at given position is a comment. Including block comments and here documents. If language is not known, or text is not parsed yet, ``False`` is returned """ return self._highlighter is not None and \ self._highlighter.isComment(self.document().findBlockByNumber(line), column)
python
{ "resource": "" }
q3336
Qutepart.isBlockComment
train
def isBlockComment(self, line, column): """Check if text at given position is a block comment. If language is not known, or text is not parsed yet, ``False`` is returned """ return self._highlighter is not None and \ self._highlighter.isBlockComment(self.document().findBlockByNumber(line), column)
python
{ "resource": "" }
q3337
Qutepart.isHereDoc
train
def isHereDoc(self, line, column): """Check if text at given position is a here document. If language is not known, or text is not parsed yet, ``False`` is returned """ return self._highlighter is not None and \ self._highlighter.isHereDoc(self.document().findBlockByNumber(line), column)
python
{ "resource": "" }
q3338
Qutepart.mapToAbsPosition
train
def mapToAbsPosition(self, line, column): """Convert line and column number to absolute position """ block = self.document().findBlockByNumber(line) if not block.isValid(): raise IndexError("Invalid line index %d" % line) if column >= block.length(): raise IndexError("Invalid column index %d" % column) return block.position() + column
python
{ "resource": "" }
q3339
Qutepart._setSolidEdgeGeometry
train
def _setSolidEdgeGeometry(self): """Sets the solid edge line geometry if needed""" if self._lineLengthEdge is not None: cr = self.contentsRect() # contents margin usually gives 1 # cursor rectangle left edge for the very first character usually # gives 4 x = self.fontMetrics().width('9' * self._lineLengthEdge) + \ self._totalMarginWidth + \ self.contentsMargins().left() + \ self.__cursorRect(self.firstVisibleBlock(), 0, offset=0).left() self._solidEdgeLine.setGeometry(QRect(x, cr.top(), 1, cr.bottom()))
python
{ "resource": "" }
q3340
Qutepart._insertNewBlock
train
def _insertNewBlock(self): """Enter pressed. Insert properly indented block """ cursor = self.textCursor() atStartOfLine = cursor.positionInBlock() == 0 with self: cursor.insertBlock() if not atStartOfLine: # if whole line is moved down - just leave it as is self._indenter.autoIndentBlock(cursor.block()) self.ensureCursorVisible()
python
{ "resource": "" }
q3341
Qutepart._currentLineExtraSelections
train
def _currentLineExtraSelections(self): """QTextEdit.ExtraSelection, which highlightes current line """ if self._currentLineColor is None: return [] def makeSelection(cursor): selection = QTextEdit.ExtraSelection() selection.format.setBackground(self._currentLineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) cursor.clearSelection() selection.cursor = cursor return selection rectangularSelectionCursors = self._rectangularSelection.cursors() if rectangularSelectionCursors: return [makeSelection(cursor) \ for cursor in rectangularSelectionCursors] else: return [makeSelection(self.textCursor())]
python
{ "resource": "" }
q3342
Qutepart._selectLines
train
def _selectLines(self, startBlockNumber, endBlockNumber): """Select whole lines """ startBlock = self.document().findBlockByNumber(startBlockNumber) endBlock = self.document().findBlockByNumber(endBlockNumber) cursor = QTextCursor(startBlock) cursor.setPosition(endBlock.position(), QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
python
{ "resource": "" }
q3343
Qutepart._onShortcutCopyLine
train
def _onShortcutCopyLine(self): """Copy selected lines to the clipboard """ lines = self.lines[self._selectedLinesSlice()] text = self._eol.join(lines) QApplication.clipboard().setText(text)
python
{ "resource": "" }
q3344
Qutepart._onShortcutPasteLine
train
def _onShortcutPasteLine(self): """Paste lines from the clipboard """ lines = self.lines[self._selectedLinesSlice()] text = QApplication.clipboard().text() if text: with self: if self.textCursor().hasSelection(): startBlockNumber, endBlockNumber = self._selectedBlockNumbers() del self.lines[self._selectedLinesSlice()] self.lines.insert(startBlockNumber, text) else: line, col = self.cursorPosition if col > 0: line = line + 1 self.lines.insert(line, text)
python
{ "resource": "" }
q3345
Qutepart._onShortcutCutLine
train
def _onShortcutCutLine(self): """Cut selected lines to the clipboard """ lines = self.lines[self._selectedLinesSlice()] self._onShortcutCopyLine() self._onShortcutDeleteLine()
python
{ "resource": "" }
q3346
Qutepart._onShortcutDuplicateLine
train
def _onShortcutDuplicateLine(self): """Duplicate selected text or current line """ cursor = self.textCursor() if cursor.hasSelection(): # duplicate selection text = cursor.selectedText() selectionStart, selectionEnd = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(selectionEnd) cursor.insertText(text) # restore selection cursor.setPosition(selectionStart) cursor.setPosition(selectionEnd, QTextCursor.KeepAnchor) self.setTextCursor(cursor) else: line = cursor.blockNumber() self.lines.insert(line + 1, self.lines[line]) self.ensureCursorVisible() self._updateExtraSelections()
python
{ "resource": "" }
q3347
Qutepart._onShortcutPrint
train
def _onShortcutPrint(self): """Ctrl+P handler. Show dialog, print file """ dialog = QPrintDialog(self) if dialog.exec_() == QDialog.Accepted: printer = dialog.printer() self.print_(printer)
python
{ "resource": "" }
q3348
Qutepart.getMargin
train
def getMargin(self, name): """Provides the requested margin. Returns a reference to the margin if found and None otherwise """ for margin in self._margins: if margin.getName() == name: return margin return None
python
{ "resource": "" }
q3349
Qutepart.delMargin
train
def delMargin(self, name): """Deletes a margin. Returns True if the margin was deleted and False otherwise. """ for index, margin in enumerate(self._margins): if margin.getName() == name: visible = margin.isVisible() margin.clear() margin.deleteLater() del self._margins[index] if visible: self.updateViewport() return True return False
python
{ "resource": "" }
q3350
_GlobalUpdateWordSetTimer.cancel
train
def cancel(self, method): """Cancel scheduled method Safe method, may be called with not-scheduled method""" if method in self._scheduledMethods: self._scheduledMethods.remove(method) if not self._scheduledMethods: self._timer.stop()
python
{ "resource": "" }
q3351
_CompletionModel.setData
train
def setData(self, wordBeforeCursor, wholeWord): """Set model information """ self._typedText = wordBeforeCursor self.words = self._makeListOfCompletions(wordBeforeCursor, wholeWord) commonStart = self._commonWordStart(self.words) self.canCompleteText = commonStart[len(wordBeforeCursor):] self.layoutChanged.emit()
python
{ "resource": "" }
q3352
_CompletionModel.data
train
def data(self, index, role): """QAbstractItemModel method implementation """ if role == Qt.DisplayRole and \ index.row() < len(self.words): text = self.words[index.row()] typed = text[:len(self._typedText)] canComplete = text[len(self._typedText):len(self._typedText) + len(self.canCompleteText)] rest = text[len(self._typedText) + len(self.canCompleteText):] if canComplete: # NOTE foreground colors are hardcoded, but I can't set background color of selected item (Qt bug?) # might look bad on some color themes return '<html>' \ '%s' \ '<font color="#e80000">%s</font>' \ '%s' \ '</html>' % (typed, canComplete, rest) else: return typed + rest else: return None
python
{ "resource": "" }
q3353
_CompletionModel._makeListOfCompletions
train
def _makeListOfCompletions(self, wordBeforeCursor, wholeWord): """Make list of completions, which shall be shown """ onlySuitable = [word for word in self._wordSet \ if word.startswith(wordBeforeCursor) and \ word != wholeWord] return sorted(onlySuitable)
python
{ "resource": "" }
q3354
_CompletionList.close
train
def close(self): """Explicitly called destructor. Removes widget from the qpart """ self._closeIfNotUpdatedTimer.stop() self._qpart.removeEventFilter(self) self._qpart.cursorPositionChanged.disconnect(self._onCursorPositionChanged) QListView.close(self)
python
{ "resource": "" }
q3355
_CompletionList.sizeHint
train
def sizeHint(self): """QWidget.sizeHint implementation Automatically resizes the widget according to rows count FIXME very bad algorithm. Remove all this margins, if you can """ width = max([self.fontMetrics().width(word) \ for word in self.model().words]) width = width * 1.4 # FIXME bad hack. invent better formula width += 30 # margin # drawn with scrollbar without +2. I don't know why rowCount = min(self.model().rowCount(), self._MAX_VISIBLE_ROWS) height = self.sizeHintForRow(0) * (rowCount + 0.5) # + 0.5 row margin return QSize(width, height)
python
{ "resource": "" }
q3356
_CompletionList._horizontalShift
train
def _horizontalShift(self): """List should be plased such way, that typed text in the list is under typed text in the editor """ strangeAdjustment = 2 # I don't know why. Probably, won't work on other systems and versions return self.fontMetrics().width(self.model().typedText()) + strangeAdjustment
python
{ "resource": "" }
q3357
_CompletionList.updateGeometry
train
def updateGeometry(self): """Move widget to point under cursor """ WIDGET_BORDER_MARGIN = 5 SCROLLBAR_WIDTH = 30 # just a guess sizeHint = self.sizeHint() width = sizeHint.width() height = sizeHint.height() cursorRect = self._qpart.cursorRect() parentSize = self.parentWidget().size() spaceBelow = parentSize.height() - cursorRect.bottom() - WIDGET_BORDER_MARGIN spaceAbove = cursorRect.top() - WIDGET_BORDER_MARGIN if height <= spaceBelow or \ spaceBelow > spaceAbove: yPos = cursorRect.bottom() if height > spaceBelow and \ spaceBelow > self.minimumHeight(): height = spaceBelow width = width + SCROLLBAR_WIDTH else: if height > spaceAbove and \ spaceAbove > self.minimumHeight(): height = spaceAbove width = width + SCROLLBAR_WIDTH yPos = max(3, cursorRect.top() - height) xPos = cursorRect.right() - self._horizontalShift() if xPos + width + WIDGET_BORDER_MARGIN > parentSize.width(): xPos = max(3, parentSize.width() - WIDGET_BORDER_MARGIN - width) self.setGeometry(xPos, yPos, width, height) self._closeIfNotUpdatedTimer.stop()
python
{ "resource": "" }
q3358
_CompletionList.eventFilter
train
def eventFilter(self, object, event): """Catch events from qpart Move selection, select item, or close themselves """ if event.type() == QEvent.KeyPress and event.modifiers() == Qt.NoModifier: if event.key() == Qt.Key_Escape: self.closeMe.emit() return True elif event.key() == Qt.Key_Down: if self._selectedIndex + 1 < self.model().rowCount(): self._selectItem(self._selectedIndex + 1) return True elif event.key() == Qt.Key_Up: if self._selectedIndex - 1 >= 0: self._selectItem(self._selectedIndex - 1) return True elif event.key() in (Qt.Key_Enter, Qt.Key_Return): if self._selectedIndex != -1: self.itemSelected.emit(self._selectedIndex) return True elif event.key() == Qt.Key_Tab: self.tabPressed.emit() return True elif event.type() == QEvent.FocusOut: self.closeMe.emit() return False
python
{ "resource": "" }
q3359
_CompletionList._selectItem
train
def _selectItem(self, index): """Select item in the list """ self._selectedIndex = index self.setCurrentIndex(self.model().createIndex(index, 0))
python
{ "resource": "" }
q3360
Completer._updateWordSet
train
def _updateWordSet(self): """Make a set of words, which shall be completed, from text """ self._wordSet = set(self._keywords) | set(self._customCompletions) start = time.time() for line in self._qpart.lines: for match in _wordRegExp.findall(line): self._wordSet.add(match) if time.time() - start > self._WORD_SET_UPDATE_MAX_TIME_SEC: """It is better to have incomplete word set, than to freeze the GUI""" break
python
{ "resource": "" }
q3361
Completer.invokeCompletionIfAvailable
train
def invokeCompletionIfAvailable(self, requestedByUser=False): """Invoke completion, if available. Called after text has been typed in qpart Returns True, if invoked """ if self._qpart.completionEnabled and self._wordSet is not None: wordBeforeCursor = self._wordBeforeCursor() wholeWord = wordBeforeCursor + self._wordAfterCursor() forceShow = requestedByUser or self._completionOpenedManually if wordBeforeCursor: if len(wordBeforeCursor) >= self._qpart.completionThreshold or forceShow: if self._widget is None: model = _CompletionModel(self._wordSet) model.setData(wordBeforeCursor, wholeWord) if self._shouldShowModel(model, forceShow): self._createWidget(model) return True else: self._widget.model().setData(wordBeforeCursor, wholeWord) if self._shouldShowModel(self._widget.model(), forceShow): self._widget.updateGeometry() return True self._closeCompletion() return False
python
{ "resource": "" }
q3362
Completer._closeCompletion
train
def _closeCompletion(self): """Close completion, if visible. Delete widget """ if self._widget is not None: self._widget.close() self._widget = None self._completionOpenedManually = False
python
{ "resource": "" }
q3363
Completer._onCompletionListItemSelected
train
def _onCompletionListItemSelected(self, index): """Item selected. Insert completion to editor """ model = self._widget.model() selectedWord = model.words[index] textToInsert = selectedWord[len(model.typedText()):] self._qpart.textCursor().insertText(textToInsert) self._closeCompletion()
python
{ "resource": "" }
q3364
Completer._onCompletionListTabPressed
train
def _onCompletionListTabPressed(self): """Tab pressed on completion list Insert completable text, if available """ canCompleteText = self._widget.model().canCompleteText if canCompleteText: self._qpart.textCursor().insertText(canCompleteText) self.invokeCompletionIfAvailable()
python
{ "resource": "" }
q3365
create_choice
train
def create_choice(klass, choices, subsets, kwargs): """Create an instance of a ``Choices`` object. Parameters ---------- klass : type The class to use to recreate the object. choices : list(tuple) A list of choices as expected by the ``__init__`` method of ``klass``. subsets : list(tuple) A tuple with an entry for each subset to create. Each entry is a list with two entries: - the name of the subsets - a list of the constants to use for this subset kwargs : dict Extra parameters expected on the ``__init__`` method of ``klass``. Returns ------- Choices A new instance of ``Choices`` (or other class defined in ``klass``). """ obj = klass(*choices, **kwargs) for subset in subsets: obj.add_subset(*subset) return obj
python
{ "resource": "" }
q3366
Choices._convert_choices
train
def _convert_choices(self, choices): """Validate each choices Parameters ---------- choices : list of tuples The list of choices to be added Returns ------- list The list of the added constants """ # Check that each new constant is unique. constants = [c[0] for c in choices] constants_doubles = [c for c in constants if constants.count(c) > 1] if constants_doubles: raise ValueError("You cannot declare two constants with the same constant name. " "Problematic constants: %s " % list(set(constants_doubles))) # Check that none of the new constants already exists. bad_constants = set(constants).intersection(self.constants) if bad_constants: raise ValueError("You cannot add existing constants. " "Existing constants: %s." % list(bad_constants)) # Check that none of the constant is an existing attributes bad_constants = [c for c in constants if hasattr(self, c)] if bad_constants: raise ValueError("You cannot add constants that already exists as attributes. " "Existing attributes: %s." % list(bad_constants)) # Check that each new value is unique. values = [c[1] for c in choices] values_doubles = [c for c in values if values.count(c) > 1] if values_doubles: raise ValueError("You cannot declare two choices with the same name." "Problematic values: %s " % list(set(values_doubles))) # Check that none of the new values already exists. try: bad_values = set(values).intersection(self.values) except TypeError: raise ValueError("One value cannot be used in: %s" % list(values)) else: if bad_values: raise ValueError("You cannot add existing values. " "Existing values: %s." % list(bad_values)) # We can now add each choice. for choice_tuple in choices: # Convert the choice tuple in a ``ChoiceEntry`` instance if it's not already done. # It allows to share choice entries between a ``Choices`` instance and its subsets. choice_entry = choice_tuple if not isinstance(choice_entry, self.ChoiceEntryClass): choice_entry = self.ChoiceEntryClass(choice_entry) # Append to the main list the choice as expected by django: (value, display name). self.append(choice_entry.choice) # And the ``ChoiceEntry`` instance to our own internal list. self.entries.append(choice_entry) # Make the value accessible via an attribute (the constant being its name). setattr(self, choice_entry.constant, choice_entry.value) # Fill dicts to access the ``ChoiceEntry`` instance by its constant, value or display.. self.constants[choice_entry.constant] = choice_entry self.values[choice_entry.value] = choice_entry self.displays[choice_entry.display] = choice_entry return constants
python
{ "resource": "" }
q3367
Choices.add_choices
train
def add_choices(self, *choices, **kwargs): """Add some choices to the current ``Choices`` instance. The given choices will be added to the existing choices. If a ``name`` attribute is passed, a new subset will be created with all the given choices. Note that it's not possible to add new choices to a subset. Parameters ---------- *choices : list of tuples It's the list of tuples to add to the ``Choices`` instance, each tuple having three entries: the constant name, the value, the display name. A dict could be added as a 4th entry in the tuple to allow setting arbitrary arguments to the final ``ChoiceEntry`` created for this choice tuple. If the first entry of ``*choices`` is a string, then it will be used as a name for a new subset that will contain all the given choices. **kwargs : dict name : string Instead of using the first entry of the ``*choices`` to pass a name of a subset to create, you can pass it via the ``name`` named argument. Example ------- >>> MY_CHOICES = Choices() >>> MY_CHOICES.add_choices(('ZERO', 0, 'zero')) >>> MY_CHOICES [('ZERO', 0, 'zero')] >>> MY_CHOICES.add_choices('SMALL', ('ONE', 1, 'one'), ('TWO', 2, 'two')) >>> MY_CHOICES [('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two')] >>> MY_CHOICES.SMALL [('ONE', 1, 'one'), ('TWO', 2, 'two')] >>> MY_CHOICES.add_choices(('THREE', 3, 'three'), ('FOUR', 4, 'four'), name='BIG') >>> MY_CHOICES [('ZERO', 0, 'zero'), ('ONE', 1, 'one'), ('TWO', 2, 'two'), ('THREE', 3, 'three'), ('FOUR', 4, 'four')] >>> MY_CHOICES.BIG [('THREE', 3, 'three'), ('FOUR', 4, 'four')] Raises ------ RuntimeError When the ``Choices`` instance is marked as not mutable, which is the case for subsets. ValueError * if the subset name is defined as first argument and as named argument. * if some constants have the same name or the same value. * if at least one constant or value already exists in the instance. """ # It the ``_mutable`` flag is falsy, which is the case for subsets, we refuse to add # new choices. if not self._mutable: raise RuntimeError("This ``Choices`` instance cannot be updated.") # Check for an optional subset name as the first argument (so the first entry of *choices). subset_name = None if choices and isinstance(choices[0], six.string_types) and choices[0] != _NO_SUBSET_NAME_: subset_name = choices[0] choices = choices[1:] # Check for an optional subset name in the named arguments. if kwargs.get('name', None): if subset_name: raise ValueError("The name of the subset cannot be defined as the first " "argument and also as a named argument") subset_name = kwargs['name'] constants = self._convert_choices(choices) # If we have a subset name, create a new subset with all the given constants. if subset_name: self.add_subset(subset_name, constants)
python
{ "resource": "" }
q3368
Choices.extract_subset
train
def extract_subset(self, *constants): """Create a subset of entries This subset is a new ``Choices`` instance, with only the wanted constants from the main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``) Parameters ---------- *constants: list The constants names of this ``Choices`` object to make available in the subset. Returns ------- Choices The newly created subset, which is a ``Choices`` object Example ------- >>> STATES = Choices( ... ('ONLINE', 1, 'Online'), ... ('DRAFT', 2, 'Draft'), ... ('OFFLINE', 3, 'Offline'), ... ) >>> STATES [('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')] >>> subset = STATES.extract_subset('DRAFT', 'OFFLINE') >>> subset [('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')] >>> subset.DRAFT 2 >>> subset.for_constant('DRAFT') is STATES.for_constant('DRAFT') True >>> subset.ONLINE Traceback (most recent call last): ... AttributeError: 'Choices' object has no attribute 'ONLINE' Raises ------ ValueError If a constant is not defined as a constant in the ``Choices`` instance. """ # Ensure that all passed constants exists as such in the list of available constants. bad_constants = set(constants).difference(self.constants) if bad_constants: raise ValueError("All constants in subsets should be in parent choice. " "Missing constants: %s." % list(bad_constants)) # Keep only entries we asked for. choice_entries = [self.constants[c] for c in constants] # Create a new ``Choices`` instance with the limited set of entries, and pass the other # configuration attributes to share the same behavior as the current ``Choices``. # Also we set ``mutable`` to False to disable the possibility to add new choices to the # subset. subset = self.__class__( *choice_entries, **{ 'dict_class': self.dict_class, 'mutable': False, } ) return subset
python
{ "resource": "" }
q3369
Choices.add_subset
train
def add_subset(self, name, constants): """Add a subset of entries under a defined name. This allow to defined a "sub choice" if a django field need to not have the whole choice available. The sub-choice is a new ``Choices`` instance, with only the wanted the constant from the main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``) The sub-choice is accessible from the main ``Choices`` by an attribute having the given name. Parameters ---------- name : string Name of the attribute that will old the new ``Choices`` instance. constants: list or tuple List of the constants name of this ``Choices`` object to make available in the subset. Returns ------- Choices The newly created subset, which is a ``Choices`` object Example ------- >>> STATES = Choices( ... ('ONLINE', 1, 'Online'), ... ('DRAFT', 2, 'Draft'), ... ('OFFLINE', 3, 'Offline'), ... ) >>> STATES [('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')] >>> STATES.add_subset('NOT_ONLINE', ('DRAFT', 'OFFLINE',)) >>> STATES.NOT_ONLINE [('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')] >>> STATES.NOT_ONLINE.DRAFT 2 >>> STATES.NOT_ONLINE.for_constant('DRAFT') is STATES.for_constant('DRAFT') True >>> STATES.NOT_ONLINE.ONLINE Traceback (most recent call last): ... AttributeError: 'Choices' object has no attribute 'ONLINE' Raises ------ ValueError * If ``name`` is already an attribute of the ``Choices`` instance. * If a constant is not defined as a constant in the ``Choices`` instance. """ # Ensure that the name is not already used as an attribute. if hasattr(self, name): raise ValueError("Cannot use '%s' as a subset name. " "It's already an attribute." % name) subset = self.extract_subset(*constants) # Make the subset accessible via an attribute. setattr(self, name, subset) self.subsets.append(name)
python
{ "resource": "" }
q3370
AutoDisplayChoices._convert_choices
train
def _convert_choices(self, choices): """Auto create display values then call super method""" final_choices = [] for choice in choices: if isinstance(choice, ChoiceEntry): final_choices.append(choice) continue original_choice = choice choice = list(choice) length = len(choice) assert 2 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,) final_choice = [] # do we have attributes? if length > 2 and isinstance(choice[-1], Mapping): final_choice.append(choice.pop()) elif length == 4: attributes = choice.pop() assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,) if attributes: final_choice.append(attributes) # the constant final_choice.insert(0, choice.pop(0)) # the db value final_choice.insert(1, choice.pop(0)) if len(choice): # we were given a display value final_choice.insert(2, choice.pop(0)) else: # no display value, we compute it from the constant final_choice.insert(2, self.display_transform(final_choice[0])) final_choices.append(final_choice) return super(AutoDisplayChoices, self)._convert_choices(final_choices)
python
{ "resource": "" }
q3371
AutoChoices.add_choices
train
def add_choices(self, *choices, **kwargs): """Disallow super method to thing the first argument is a subset name""" return super(AutoChoices, self).add_choices(_NO_SUBSET_NAME_, *choices, **kwargs)
python
{ "resource": "" }
q3372
AutoChoices._convert_choices
train
def _convert_choices(self, choices): """Auto create db values then call super method""" final_choices = [] for choice in choices: if isinstance(choice, ChoiceEntry): final_choices.append(choice) continue original_choice = choice if isinstance(choice, six.string_types): if choice == _NO_SUBSET_NAME_: continue choice = [choice, ] else: choice = list(choice) length = len(choice) assert 1 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,) final_choice = [] # do we have attributes? if length > 1 and isinstance(choice[-1], Mapping): final_choice.append(choice.pop()) elif length == 4: attributes = choice.pop() assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,) if attributes: final_choice.append(attributes) # the constant final_choice.insert(0, choice.pop(0)) if len(choice): # we were given a db value final_choice.insert(1, choice.pop(0)) if len(choice): # we were given a display value final_choice.insert(2, choice.pop(0)) else: # set None to compute it later final_choice.insert(1, None) if final_choice[1] is None: # no db value, we compute it from the constant final_choice[1] = self.value_transform(final_choice[0]) final_choices.append(final_choice) return super(AutoChoices, self)._convert_choices(final_choices)
python
{ "resource": "" }
q3373
NamedExtendedChoiceFormField.to_python
train
def to_python(self, value): """Convert the constant to the real choice value.""" # ``is_required`` is already checked in ``validate``. if value is None: return None # Validate the type. if not isinstance(value, six.string_types): raise forms.ValidationError( "Invalid value type (should be a string).", code='invalid-choice-type', ) # Get the constant from the choices object, raising if it doesn't exist. try: final = getattr(self.choices, value) except AttributeError: available = '[%s]' % ', '.join(self.choices.constants) raise forms.ValidationError( "Invalid value (not in available choices. Available ones are: %s" % available, code='non-existing-choice', ) return final
python
{ "resource": "" }
q3374
create_choice_attribute
train
def create_choice_attribute(creator_type, value, choice_entry): """Create an instance of a subclass of ChoiceAttributeMixin for the given value. Parameters ---------- creator_type : type ``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value`` class-method. value : ? The value for which we want to create an instance of a new subclass of ``creator_type``. choice_entry: ChoiceEntry The ``ChoiceEntry`` instance that hold the current value, used to access its constant, value and display name. Returns ------- ChoiceAttributeMixin An instance of a subclass of ``creator_type`` for the given value """ klass = creator_type.get_class_for_value(value) return klass(value, choice_entry)
python
{ "resource": "" }
q3375
ChoiceAttributeMixin.get_class_for_value
train
def get_class_for_value(cls, value): """Class method to construct a class based on this mixin and the type of the given value. Parameters ---------- value: ? The value from which to extract the type to create the new class. Notes ----- The create classes are cached (in ``cls.__classes_by_type``) to avoid recreating already created classes. """ type_ = value.__class__ # Check if the type is already a ``ChoiceAttribute`` if issubclass(type_, ChoiceAttributeMixin): # In this case we can return this type return type_ # Create a new class only if it wasn't already created for this type. if type_ not in cls._classes_by_type: # Compute the name of the class with the name of the type. class_name = str('%sChoiceAttribute' % type_.__name__.capitalize()) # Create a new class and save it in the cache. cls._classes_by_type[type_] = type(class_name, (cls, type_), { 'creator_type': cls, }) # Return the class from the cache based on the type. return cls._classes_by_type[type_]
python
{ "resource": "" }
q3376
ChoiceEntry._get_choice_attribute
train
def _get_choice_attribute(self, value): """Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the given value. Raises ------ ValueError If the value is None, as we cannot really subclass NoneType. """ if value is None: raise ValueError('Using `None` in a `Choices` object is not supported. You may ' 'use an empty string.') return create_choice_attribute(self.ChoiceAttributeMixin, value, self)
python
{ "resource": "" }
q3377
Session.urljoin
train
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. """ return "/".join(map(lambda x: str(x).rstrip('/'), args)).rstrip('/')
python
{ "resource": "" }
q3378
Session.server_version
train
def server_version(self): """ Special method for getting server version. Because of different behaviour on different versions of server, we have to pass different headers to the endpoints. This method requests the version from server and caches it in internal variable, so other resources could use it. :return: server version parsed from `about` page. """ if self.__server_version is None: from yagocd.resources.info import InfoManager self.__server_version = InfoManager(self).version return self.__server_version
python
{ "resource": "" }
q3379
JobInstance.pipeline_name
train
def pipeline_name(self): """ Get pipeline name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name. """ if 'pipeline_name' in self.data and self.data.pipeline_name: return self.data.get('pipeline_name') elif self.stage.pipeline is not None: return self.stage.pipeline.data.name else: return self.stage.data.pipeline_name
python
{ "resource": "" }
q3380
JobInstance.pipeline_counter
train
def pipeline_counter(self): """ Get pipeline counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter. """ if 'pipeline_counter' in self.data and self.data.pipeline_counter: return self.data.get('pipeline_counter') elif self.stage.pipeline is not None: return self.stage.pipeline.data.counter else: return self.stage.data.pipeline_counter
python
{ "resource": "" }
q3381
JobInstance.stage_name
train
def stage_name(self): """ Get stage name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the stage. :return: stage name. """ if 'stage_name' in self.data and self.data.stage_name: return self.data.get('stage_name') else: return self.stage.data.name
python
{ "resource": "" }
q3382
JobInstance.stage_counter
train
def stage_counter(self): """ Get stage counter of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get counter of the stage. :return: stage counter. """ if 'stage_counter' in self.data and self.data.stage_counter: return self.data.get('stage_counter') else: return self.stage.data.counter
python
{ "resource": "" }
q3383
JobInstance.artifacts
train
def artifacts(self): """ Property for accessing artifact manager of the current job. :return: instance of :class:`yagocd.resources.artifact.ArtifactManager` :rtype: yagocd.resources.artifact.ArtifactManager """ return ArtifactManager( session=self._session, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.stage_name, stage_counter=self.stage_counter, job_name=self.data.name )
python
{ "resource": "" }
q3384
StageInstance.url
train
def url(self): """ Returns url for accessing stage instance. """ return "{server_url}/go/pipelines/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}".format( server_url=self._session.server_url, pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.data.name, stage_counter=self.data.counter, )
python
{ "resource": "" }
q3385
StageInstance.pipeline_name
train
def pipeline_name(self): """ Get pipeline name of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get name of the pipeline. :return: pipeline name. """ if 'pipeline_name' in self.data: return self.data.get('pipeline_name') elif self.pipeline is not None: return self.pipeline.data.name
python
{ "resource": "" }
q3386
StageInstance.pipeline_counter
train
def pipeline_counter(self): """ Get pipeline counter of current stage instance. Because instantiating stage instance could be performed in different ways and those return different results, we have to check where from to get counter of the pipeline. :return: pipeline counter. """ if 'pipeline_counter' in self.data: return self.data.get('pipeline_counter') elif self.pipeline is not None: return self.pipeline.data.counter
python
{ "resource": "" }
q3387
StageInstance.cancel
train
def cancel(self): """ Cancel an active stage of a specified stage. :return: a text confirmation. """ return self._manager.cancel(pipeline_name=self.pipeline_name, stage_name=self.stage_name)
python
{ "resource": "" }
q3388
StageInstance.jobs
train
def jobs(self): """ Method for getting jobs from stage instance. :return: arrays of jobs. :rtype: list of yagocd.resources.job.JobInstance """ jobs = list() for data in self.data.jobs: jobs.append(JobInstance(session=self._session, data=data, stage=self)) return jobs
python
{ "resource": "" }
q3389
StageInstance.job
train
def job(self, name): """ Method for searching specific job by it's name. :param name: name of the job to search. :return: found job or None. :rtype: yagocd.resources.job.JobInstance """ for job in self.jobs(): if job.data.name == name: return job
python
{ "resource": "" }
q3390
PipelineEntity.config
train
def config(self): """ Property for accessing pipeline configuration. :rtype: yagocd.resources.pipeline_config.PipelineConfigManager """ return PipelineConfigManager(session=self._session, pipeline_name=self.data.name)
python
{ "resource": "" }
q3391
PipelineEntity.history
train
def history(self, offset=0): """ The pipeline history allows users to list pipeline instances. :param offset: number of pipeline instances to be skipped. :return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: list of yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.history(name=self.data.name, offset=offset)
python
{ "resource": "" }
q3392
PipelineEntity.get
train
def get(self, counter): """ Gets pipeline instance object. :param counter pipeline counter: :return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`. :rtype: yagocd.resources.pipeline.PipelineInstance """ return self._pipeline.get(name=self.data.name, counter=counter)
python
{ "resource": "" }
q3393
PipelineEntity.pause
train
def pause(self, cause): """ Pause the current pipeline. :param cause: reason for pausing the pipeline. """ self._pipeline.pause(name=self.data.name, cause=cause)
python
{ "resource": "" }
q3394
PipelineEntity.schedule
train
def schedule(self, materials=None, variables=None, secure_variables=None): """ Scheduling allows user to trigger a specific pipeline. :param materials: material revisions to use. :param variables: environment variables to set. :param secure_variables: secure environment variables to set. :return: a text confirmation. """ return self._pipeline.schedule( name=self.data.name, materials=materials, variables=variables, secure_variables=secure_variables )
python
{ "resource": "" }
q3395
PipelineInstance.stages
train
def stages(self): """ Method for getting stages from pipeline instance. :return: arrays of stages :rtype: list of yagocd.resources.stage.StageInstance """ stages = list() for data in self.data.stages: stages.append(StageInstance(session=self._session, data=data, pipeline=self)) return stages
python
{ "resource": "" }
q3396
PipelineInstance.stage
train
def stage(self, name): """ Method for searching specific stage by it's name. :param name: name of the stage to search. :return: found stage or None. :rtype: yagocd.resources.stage.StageInstance """ for stage in self.stages(): if stage.data.name == name: return stage
python
{ "resource": "" }
q3397
RequireParamMixin._require_param
train
def _require_param(self, name, values): """ Method for finding the value for the given parameter name. The value for the parameter could be extracted from two places: * `values` dictionary * `self._<name>` attribute The use case for this method is that some resources are nested and managers could have dependencies on parent data, for example :class:`ArtifactManager` should know about pipeline, stage and job in order to get data for specific instance of artifact. In case we obtain this information from pipeline and going down to the artifact, it will be provided in constructor for that manager. But in case we would like to use functionality of specific manager without getting parents -- directly from :class:`Yagocd`, then we have to be able to execute method with given parameters for parents. Current method - `_require_param` - is used to find out which parameters should one use: either provided at construction time and stored as `self._<name>` or provided as function arguments. :param name: name of the parameter, which value to extract. :param values: dictionary, which could contain the value for our parameter. :return: founded value or raises `ValueError`. """ values = [values[name]] instance_name = '_{}'.format(name) values.append(getattr(self, instance_name, None)) try: return next(item for item in values if item is not None) except StopIteration: raise ValueError("The value for parameter '{}' is required!".format(name))
python
{ "resource": "" }
q3398
BaseManager._accept_header
train
def _accept_header(self): """ Method for determining correct `Accept` header. Different resources and different GoCD version servers prefer a diverse headers. In order to manage all of them, this method tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided, if would simply return default `ACCEPT_HEADER`. Though if some manager specifies `VERSION_TO_ACCEPT_HEADER` class variable, then it should be a dictionary: keys should be a versions and values should be desired accept headers. Choosing is pessimistic: if version of a server is less or equal to one of the dictionary, the value of that key would be used. :return: accept header to use in request. """ if not self.VERSION_TO_ACCEPT_HEADER: return self.ACCEPT_HEADER return YagocdUtil.choose_option( version_to_options=self.VERSION_TO_ACCEPT_HEADER, default=self.ACCEPT_HEADER, server_version=self._session.server_version )
python
{ "resource": "" }
q3399
Artifact.walk
train
def walk(self, topdown=True): """ Artifact tree generator - analogue of `os.walk`. :param topdown: if is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up. :rtype: collections.Iterator[ (str, list[yagocd.resources.artifact.Artifact], list[yagocd.resources.artifact.Artifact]) ] """ return self._manager.walk(top=self._path, topdown=topdown)
python
{ "resource": "" }