_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q3200
JsonMarshaler.emit_map
train
def emit_map(self, m, _, cache): """Emits array as per default JSON spec.""" self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
python
{ "resource": "" }
q3201
Decoder.decode_list
train
def decode_list(self, node, cache, as_map_key): """Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function. """ if node: if node[0] == MAP_AS_ARR: ...
python
{ "resource": "" }
q3202
Decoder.decode_string
train
def decode_string(self, string, cache, as_map_key): """Decode a string - arguments follow the same convention as the top-level 'decode' function. """ if is_cache_key(string): return self.parse_string(cache.decode(string, as_map_key), cache...
python
{ "resource": "" }
q3203
UuidHandler.from_rep
train
def from_rep(u): """Given a string, return a UUID object.""" if isinstance(u, pyversion.string_types): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int...
python
{ "resource": "" }
q3204
PacketIn.in_port
train
def in_port(self): """Retrieve the 'in_port' that generated the PacketIn. This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on the `oxm_match_fields` field from `match` field and return its value, if the OXM exists. Returns: The integer number of th...
python
{ "resource": "" }
q3205
PacketOut._update_actions_len
train
def _update_actions_len(self): """Update the actions_len field based on actions value.""" if isinstance(self.actions, ListOfActions): self.actions_len = self.actions.get_size() else: self.actions_len = ListOfActions(self.actions).get_size()
python
{ "resource": "" }
q3206
PacketOut._validate_in_port
train
def _validate_in_port(self): """Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: Val...
python
{ "resource": "" }
q3207
new_message_from_message_type
train
def new_message_from_message_type(message_type): """Given an OpenFlow Message Type, return an empty message of that type. Args: messageType (:class:`~pyof.v0x01.common.header.Type`): Python-openflow message. Returns: Empty OpenFlow message of the requested message type. Ra...
python
{ "resource": "" }
q3208
new_message_from_header
train
def new_message_from_header(header): """Given an OF Header, return an empty message of header's message_type. Args: header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header. Returns: Empty OpenFlow message of the same type of message_type attribute from the given header....
python
{ "resource": "" }
q3209
unpack_message
train
def unpack_message(buffer): """Unpack the whole buffer, including header pack. Args: buffer (bytes): Bytes representation of a openflow message. Returns: object: Instance of openflow message. """ hdr_size = Header().get_size() hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr...
python
{ "resource": "" }
q3210
MultipartReply._unpack_body
train
def _unpack_body(self): """Unpack `body` replace it by the result.""" obj = self._get_body_instance() obj.unpack(self.body.value) self.body = obj
python
{ "resource": "" }
q3211
OxmTLV.unpack
train
def unpack(self, buff, offset=0): """Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, offset) # Recover field from field_and_hasmask...
python
{ "resource": "" }
q3212
OxmTLV._unpack_oxm_field
train
def _unpack_oxm_field(self): """Unpack oxm_field from oxm_field_and_mask. Returns: :class:`OxmOfbMatchField`, int: oxm_field from oxm_field_and_mask. Raises: ValueError: If oxm_class is OFPXMC_OPENFLOW_BASIC but :class:`OxmOfbMatchField` has no such inte...
python
{ "resource": "" }
q3213
OxmTLV._update_length
train
def _update_length(self): """Update length field. Update the oxm_length field with the packed payload length. """ payload = type(self).oxm_value.pack(self.oxm_value) self.oxm_length = len(payload)
python
{ "resource": "" }
q3214
OxmTLV.pack
train
def pack(self, value=None): """Join oxm_hasmask bit and 7-bit oxm_field.""" if value is not None: return value.pack() # Set oxm_field_and_mask instance attribute # 1. Move field integer one bit to the left try: field_int = self._get_oxm_field_int() ...
python
{ "resource": "" }
q3215
OxmTLV._get_oxm_field_int
train
def _get_oxm_field_int(self): """Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and ...
python
{ "resource": "" }
q3216
Match.pack
train
def pack(self, value=None): """Pack and complete the last byte by padding.""" if isinstance(value, Match): return value.pack() elif value is None: self._update_match_length() packet = super().pack() return self._complete_last_byte(packet) r...
python
{ "resource": "" }
q3217
Match.unpack
train
def unpack(self, buff, offset=0): """Discard padding bytes using the unpacked length attribute.""" begin = offset for name, value in list(self.get_class_attributes())[:-1]: size = self._unpack_attribute(name, value, buff, begin) begin += size self._unpack_attribut...
python
{ "resource": "" }
q3218
Match.get_field
train
def get_field(self, field_type): """Return the value for the 'field_type' field in oxm_match_fields. Args: field_type (~pyof.v0x04.common.flow_match.OxmOfbMatchField, ~pyof.v0x04.common.flow_match.OxmMatchFields): The type of the OXM field you want th...
python
{ "resource": "" }
q3219
GenericType.value
train
def value(self): """Return this type's value. Returns: object: The value of an enum, bitmask, etc. """ if self.isenum(): if isinstance(self._value, self.enum_ref): return self._value.value return self._value elif self.is_bitma...
python
{ "resource": "" }
q3220
GenericType.pack
train
def pack(self, value=None): r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() ...
python
{ "resource": "" }
q3221
MetaStruct._header_message_type_update
train
def _header_message_type_update(obj, attr): """Update the message type on the header. Set the message_type of the header according to the message_type of the parent class. """ old_enum = obj.message_type new_header = attr[1] new_enum = new_header.__class__.messag...
python
{ "resource": "" }
q3222
MetaStruct.get_pyof_version
train
def get_pyof_version(module_fullname): """Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow ver...
python
{ "resource": "" }
q3223
MetaStruct.replace_pyof_version
train
def replace_pyof_version(module_fullname, version): """Replace the OF Version of a module fullname. Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on a new 'version' (eg. 'pyof.v0x02.common.header'). Args: module_fullname (str): The fullname of the modu...
python
{ "resource": "" }
q3224
MetaStruct.get_pyof_obj_new_version
train
def get_pyof_obj_new_version(name, obj, new_version): r"""Return a class attribute on a different pyof version. This method receives the name of a class attribute, the class attribute itself (object) and an openflow version. The attribute will be evaluated and from it we will recover it...
python
{ "resource": "" }
q3225
GenericStruct._validate_attributes_type
train
def _validate_attributes_type(self): """Validate the type of each attribute.""" for _attr, _class in self._get_attributes(): if isinstance(_attr, _class): return True elif issubclass(_class, GenericType): if GenericStruct._attr_fits_into_class(_att...
python
{ "resource": "" }
q3226
GenericStruct.get_class_attributes
train
def get_class_attributes(cls): """Return a generator for class attributes' names and value. This method strict relies on the PEP 520 (Preserving Class Attribute Definition Order), implemented on Python 3.6. So, if this behaviour changes this whole lib can loose its functionality (since ...
python
{ "resource": "" }
q3227
GenericStruct._get_instance_attributes
train
def _get_instance_attributes(self): """Return a generator for instance attributes' name and value. .. code-block:: python3 for _name, _value in self._get_instance_attributes(): print("attribute name: {}".format(_name)) print("attribute value: {}".format(_val...
python
{ "resource": "" }
q3228
GenericStruct._get_attributes
train
def _get_attributes(self): """Return a generator for instance and class attribute. .. code-block:: python3 for instance_attribute, class_attribute in self._get_attributes(): print("Instance Attribute: {}".format(instance_attribute)) print("Class Attribute: {...
python
{ "resource": "" }
q3229
GenericStruct._get_named_attributes
train
def _get_named_attributes(self): """Return generator for attribute's name, instance and class values. Add attribute name to meth:`_get_attributes` for a better debugging message, so user can find the error easier. Returns: generator: Tuple with attribute's name, instance an...
python
{ "resource": "" }
q3230
GenericStruct.get_size
train
def get_size(self, value=None): """Calculate the total struct size in bytes. For each struct attribute, sum the result of each one's ``get_size()`` method. Args: value: In structs, the user can assign other value instead of a class' instance. Return...
python
{ "resource": "" }
q3231
GenericMessage.pack
train
def pack(self, value=None): """Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a sw...
python
{ "resource": "" }
q3232
GenericBitMask.names
train
def names(self): """List of selected enum names. Returns: list: Enum names. """ result = [] for key, value in self.iteritems(): if value & self.bitmask: result.append(key) return result
python
{ "resource": "" }
q3233
Match.fill_wildcards
train
def fill_wildcards(self, field=None, value=0): """Update wildcards attribute. This method update a wildcards considering the attributes of the current instance. Args: field (str): Name of the updated field. value (GenericType): New value used in the field. ...
python
{ "resource": "" }
q3234
ActionSetField.pack
train
def pack(self, value=None): """Pack this structure updating the length and padding it.""" self._update_length() packet = super().pack() return self._complete_last_byte(packet)
python
{ "resource": "" }
q3235
ActionSetField._update_length
train
def _update_length(self): """Update the length field of the struct.""" action_length = 4 + len(self.field.pack()) overflow = action_length % 8 self.length = action_length if overflow: self.length = action_length + 8 - overflow
python
{ "resource": "" }
q3236
VLAN._validate
train
def _validate(self): """Assure this is a valid VLAN header instance.""" if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
python
{ "resource": "" }
q3237
Ethernet._get_vlan_length
train
def _get_vlan_length(buff): """Return the total length of VLAN tags in a given Ethernet buffer.""" length = 0 begin = 12 while(buff[begin:begin+2] in (EtherType.VLAN.to_bytes(2, 'big'), EtherType.VLAN_QINQ.to_bytes(2, 'big'))): length +=...
python
{ "resource": "" }
q3238
GenericTLV.pack
train
def pack(self, value=None): """Pack the TLV in a binary representation. Returns: bytes: Binary representation of the struct object. Raises: :exc:`~.exceptions.ValidationError`: If validation fails. """ if value is None: output = self.header....
python
{ "resource": "" }
q3239
GenericTLV.get_size
train
def get_size(self, value=None): """Return struct size. Returns: int: Returns the struct size based on inner attributes. """ if isinstance(value, type(self)): return value.get_size() return 2 + self.length
python
{ "resource": "" }
q3240
IPv4._update_checksum
train
def _update_checksum(self): """Update the packet checksum to enable integrity check.""" source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8)...
python
{ "resource": "" }
q3241
TLVWithSubType.value
train
def value(self): """Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated. """ binary = UBInt8(self.sub_type).pack() + self.sub_value.pack() return BinaryData(binary)
python
{ "resource": "" }
q3242
validate_packet
train
def validate_packet(packet): """Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid. """ if not isinstance(packet, bytes): raise UnpackException('invalid packet') packet_length = len(packet) if packet_length < 8 or packet_length > 2**16: ...
python
{ "resource": "" }
q3243
unpack
train
def unpack(packet): """Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked. """ validate_packet(pa...
python
{ "resource": "" }
q3244
ErrorMsg.unpack
train
def unpack(self, buff, offset=0): """Unpack binary data into python object.""" super().unpack(buff, offset) code_class = ErrorType(self.error_type).get_class() self.code = code_class(self.code)
python
{ "resource": "" }
q3245
Bookmarks._createAction
train
def _createAction(self, widget, iconFileName, text, shortcut, slot): """Create QAction with given parameters and add to the widget """ icon = qutepart.getIcon(iconFileName) action = QAction(icon, text, widget) action.setShortcut(QKeySequence(shortcut)) action.setShortcutC...
python
{ "resource": "" }
q3246
Bookmarks.clear
train
def clear(self, startBlock, endBlock): """Clear bookmarks on block range including start and end """ for block in qutepart.iterateBlocksFrom(startBlock): self._setBlockMarked(block, False) if block == endBlock: break
python
{ "resource": "" }
q3247
BracketHighlighter._makeMatchSelection
train
def _makeMatchSelection(self, block, columnIndex, matched): """Make matched or unmatched QTextEdit.ExtraSelection """ selection = QTextEdit.ExtraSelection() if matched: bgColor = Qt.green else: bgColor = Qt.red selection.format.setBackground(bgCo...
python
{ "resource": "" }
q3248
BracketHighlighter._highlightBracket
train
def _highlightBracket(self, bracket, qpart, block, columnIndex): """Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's """ try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _Time...
python
{ "resource": "" }
q3249
BracketHighlighter.extraSelections
train
def extraSelections(self, qpart, block, columnIndex): """List of QTextEdit.ExtraSelection's, which highlighte brackets """ blockText = block.text() if columnIndex < len(blockText) and \ blockText[columnIndex] in self._ALL_BRACKETS and \ qpart.isCode(block, colu...
python
{ "resource": "" }
q3250
_cmpFormatRanges
train
def _cmpFormatRanges(a, b): """PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance """ if a.format == b.format and \ a.start == b.start and \ a.length == b.length: return 0 ...
python
{ "resource": "" }
q3251
SyntaxHighlighter.isCode
train
def isCode(self, block, column): """Check if character at column is a a code """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isCode(data, column)
python
{ "resource": "" }
q3252
SyntaxHighlighter.isComment
train
def isComment(self, block, column): """Check if character at column is a comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isComment(data, column)
python
{ "resource": "" }
q3253
SyntaxHighlighter.isBlockComment
train
def isBlockComment(self, block, column): """Check if character at column is a block comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isBlockComment(data, column)
python
{ "resource": "" }
q3254
SyntaxHighlighter.isHereDoc
train
def isHereDoc(self, block, column): """Check if character at column is a here document """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
python
{ "resource": "" }
q3255
Lines._atomicModification
train
def _atomicModification(func): """Decorator Make document modification atomic """ def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
python
{ "resource": "" }
q3256
Lines._checkAndConvertIndex
train
def _checkAndConvertIndex(self, index): """Check integer index, convert from less than zero notation """ if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
python
{ "resource": "" }
q3257
Lines.append
train
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
python
{ "resource": "" }
q3258
Lines.insert
train
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(tex...
python
{ "resource": "" }
q3259
IndentAlgRuby._isLastCodeColumn
train
def _isLastCodeColumn(self, block, column): """Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. """ return column >= self._lastColumn(block) or \ ...
python
{ "resource": "" }
q3260
IndentAlgRuby.findStmtStart
train
def findStmtStart(self, block): """Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0 """ prevBlock = self._prevNonCommentBlock(block) while prevBlock.isValid() and \ (((prevBlock == block.previous()) and self._isBl...
python
{ "resource": "" }
q3261
IndentAlgRuby._isValidTrigger
train
def _isValidTrigger(block, ch): """check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user """ if ch == "" or ch == "\n": return True # Explicit align or new line match = rxUnindent.match(block.text()) ...
python
{ "resource": "" }
q3262
IndentAlgRuby.findPrevStmt
train
def findPrevStmt(self, block): """Returns a tuple that contains the first and last line of the previous statement before line. """ stmtEnd = self._prevNonCommentBlock(block) stmtStart = self.findStmtStart(stmtEnd) return Statement(self._qpart, stmtStart, stmtEnd)
python
{ "resource": "" }
q3263
HTMLDelegate.paint
train
def paint(self, painter, option, index): """QStyledItemDelegate.paint implementation """ option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItem(option) self.initStyleOption(options,index) style = QApplication.style() if options.wi...
python
{ "resource": "" }
q3264
RectangularSelection.isDeleteKeyEvent
train
def isDeleteKeyEvent(self, keyEvent): """Check if key event should be handled as Delete command""" return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
python
{ "resource": "" }
q3265
RectangularSelection.delete
train
def delete(self): """Del or Backspace pressed. Delete selection""" with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
python
{ "resource": "" }
q3266
RectangularSelection.isExpandKeyEvent
train
def isExpandKeyEvent(self, keyEvent): """Check if key event should expand rectangular selection""" return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, ...
python
{ "resource": "" }
q3267
RectangularSelection.onExpandKeyEvent
train
def onExpandKeyEvent(self, keyEvent): """One of expand selection key events""" if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpa...
python
{ "resource": "" }
q3268
RectangularSelection._realToVisibleColumn
train
def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and visible position differs This function converts real to visible """ generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(gen...
python
{ "resource": "" }
q3269
RectangularSelection._visibleToRealColumn
train
def _visibleToRealColumn(self, text, visiblePos): """If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short """ if visiblePos ==...
python
{ "resource": "" }
q3270
RectangularSelection.cursors
train
def cursors(self): """Cursors for rectangular selection. 1 cursor for every line """ cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - curre...
python
{ "resource": "" }
q3271
RectangularSelection.selections
train
def selections(self): """Build list of extra selections for rectangular selection""" selections = [] cursors = self.cursors() if cursors: background = self._qpart.palette().color(QPalette.Highlight) foreground = self._qpart.palette().color(QPalette.HighlightedText...
python
{ "resource": "" }
q3272
RectangularSelection.copy
train
def copy(self): """Copy to the clipboard""" data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(da...
python
{ "resource": "" }
q3273
RectangularSelection.cut
train
def cut(self): """Cut action. Copy and delete """ cursorPos = self._qpart.cursorPosition topLeft = (min(self._start[0], cursorPos[0]), min(self._start[1], cursorPos[1])) self.copy() self.delete() """Move cursor to top-left corner of the selecti...
python
{ "resource": "" }
q3274
RectangularSelection._indentUpTo
train
def _indentUpTo(self, text, width): """Add space to text, so text width will be at least width. Return text, which must be added """ visibleTextWidth = self._realToVisibleColumn(text, len(text)) diff = width - visibleTextWidth if diff <= 0: return '' e...
python
{ "resource": "" }
q3275
RectangularSelection.paste
train
def paste(self, mimeData): """Paste recrangular selection. Add space at the beginning of line, if necessary """ if self.isActive(): self.delete() elif self._qpart.textCursor().hasSelection(): self._qpart.textCursor().deleteChar() text = bytes(mime...
python
{ "resource": "" }
q3276
MarginBase.__allocateBits
train
def __allocateBits(self): """Allocates the bit range depending on the required bit count """ if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return # Build a list of occupied ranges ...
python
{ "resource": "" }
q3277
MarginBase.__updateRequest
train
def __updateRequest(self, rect, dy): """Repaint line number area if necessary """ if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): # if block heig...
python
{ "resource": "" }
q3278
MarginBase.setBlockValue
train
def setBlockValue(self, block, value): """Sets the required value to the block without damaging the other bits """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") if value < 0: ...
python
{ "resource": "" }
q3279
MarginBase.getBlockValue
train
def getBlockValue(self, block): """Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided. """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + ...
python
{ "resource": "" }
q3280
MarginBase.clear
train
def clear(self): """Convenience method to reset all the block values to 0 """ if self._bit_count == 0: return block = self._qpart.document().begin() while block.isValid(): if self.getBlockValue(block): self.setBlockValue(block, 0) ...
python
{ "resource": "" }
q3281
SyntaxManager._getSyntaxByXmlFileName
train
def _getSyntaxByXmlFileName(self, xmlFileName): """Get syntax by its xml file name """ import qutepart.syntax.loader # delayed import for avoid cross-imports problem with self._loadedSyntaxesLock: if not xmlFileName in self._loadedSyntaxes: xmlFilePath = os....
python
{ "resource": "" }
q3282
SyntaxManager._getSyntaxByLanguageName
train
def _getSyntaxByLanguageName(self, syntaxName): """Get syntax by its name. Name is defined in the xml file """ xmlFileName = self._syntaxNameToXmlFileName[syntaxName] return self._getSyntaxByXmlFileName(xmlFileName)
python
{ "resource": "" }
q3283
SyntaxManager._getSyntaxBySourceFileName
train
def _getSyntaxBySourceFileName(self, name): """Get syntax by source name of file, which is going to be highlighted """ for regExp, xmlFileName in self._extensionToXmlFileName.items(): if regExp.match(name): return self._getSyntaxByXmlFileName(xmlFileName) else...
python
{ "resource": "" }
q3284
ContextStack.pop
train
def pop(self, count): """Returns new context stack, which doesn't contain few levels """ if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], ...
python
{ "resource": "" }
q3285
ContextStack.append
train
def append(self, context, data): """Returns new context, which contains current stack and new frame """ return ContextStack(self._contexts + [context], self._data + [data])
python
{ "resource": "" }
q3286
ContextSwitcher.getNextContextStack
train
def getNextContextStack(self, contextStack, data=None): """Apply modification to the contextStack. This method never modifies input parameter list """ if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: ...
python
{ "resource": "" }
q3287
StringDetect._makeDynamicSubsctitutions
train
def _makeDynamicSubsctitutions(string, contextData): """For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension. """ def _replaceFunc(escapeMatchObject): stringIndex = escapeMatchObject.group(0)[1] index = int(strin...
python
{ "resource": "" }
q3288
RegExpr._tryMatch
train
def _tryMatch(self, textToMatchObject): """Tries to parse text. If matched - saves data for dynamic context """ # Special case. if pattern starts with \b, we have to check it manually, # because string is passed to .match(..) without beginning if self.wordStart and \ (...
python
{ "resource": "" }
q3289
RegExpr._compileRegExp
train
def _compileRegExp(string, insensitive, minimal): """Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE """ flags = 0 if insensitive: flags = re.IGNORECASE string = string.replac...
python
{ "resource": "" }
q3290
AbstractNumberRule._countDigits
train
def _countDigits(self, text): """Count digits at start of text """ index = 0 while index < len(text): if not text[index].isdigit(): break index += 1 return index
python
{ "resource": "" }
q3291
Parser.highlightBlock
train
def highlightBlock(self, text, prevContextStack): """Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters """ if prevContextStack is not...
python
{ "resource": "" }
q3292
IndentAlgCStyle.findLeftBrace
train
def findLeftBrace(self, block, column): """Search for a corresponding '{' and return its indentation If not found return None """ block, column = self.findBracketBackward(block, column, '{') # raise ValueError if not found try: block, column = self.tryParenthesisBef...
python
{ "resource": "" }
q3293
IndentAlgCStyle.trySwitchStatement
train
def trySwitchStatement(self, block): """Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found. """ if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): ...
python
{ "resource": "" }
q3294
IndentAlgCStyle.indentLine
train
def indentLine(self, block, autoIndent): """ Indent line. Return filler or null. """ indent = None if indent is None: indent = self.tryMatchedAnchor(block, autoIndent) if indent is None: indent = self.tryCComment(block) if indent is None an...
python
{ "resource": "" }
q3295
IndentAlgScheme._findExpressionEnd
train
def _findExpressionEnd(self, block): """Find end of the last expression """ while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
python
{ "resource": "" }
q3296
IndentAlgScheme._lastWord
train
def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: ...
python
{ "resource": "" }
q3297
IndentAlgScheme._findExpressionStart
train
def _findExpressionStart(self, block): """Find start of not finished expression Raise UserWarning, if not found """ # raise expession on next level, if not found expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] ...
python
{ "resource": "" }
q3298
_getSmartIndenter
train
def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ...
python
{ "resource": "" }
q3299
Indenter.autoIndentBlock
train
def autoIndentBlock(self, block, char='\n'): """Indent block after Enter pressed or trigger character typed """ currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartInde...
python
{ "resource": "" }