_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| 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)
|
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:
# key must be decoded before value for caching to work.
returned_dict = {}
for k, v in pairs(node[1:]):
key = self._decode(k, cache, True)
val = self._decode(v, cache, as_map_key)
|
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),
|
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 =
|
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:
|
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):
|
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
|
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.
Raises:
KytosUndefinedMessageType: Unkown Message_Type.
"""
message_type =
|
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.
The header attribute of the message will be populated.
Raises:
KytosUndefinedMessageType: Unkown Message_Type.
"""
message_type = header.message_type
if not isinstance(message_type, Type):
try:
if isinstance(message_type, str):
|
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()
|
python
|
{
"resource": ""
}
|
q3210
|
MultipartReply._unpack_body
|
train
|
def _unpack_body(self):
"""Unpack `body` replace it by the result."""
|
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.
try:
self.oxm_field = self._unpack_oxm_field()
except ValueError as exception:
raise UnpackException(exception)
# The last bit of field_and_mask is oxm_hasmask
self.oxm_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 integer value.
"""
|
python
|
{
"resource": ""
}
|
q3213
|
OxmTLV._update_length
|
train
|
def _update_length(self):
"""Update length field.
Update the oxm_length field with the packed payload length.
"""
|
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:
|
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
|
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()
|
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
|
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):
|
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
|
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()
b'\x01'
>>> objectA.pack(objectB)
b'\x05'
Args:
value: If the value is None, then we will pack the value of the
current instance. Otherwise, if value is an instance of the
same type as the current instance, then we call the pack of the
value object. Otherwise, we will use the current instance pack
method on the passed value.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.exceptions.BadValueException`: If the value does not
fit the binary format.
"""
if isinstance(value, type(self)):
|
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__.message_type.enum_ref
#: This 'if' will be removed on the future with an
|
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 version, on the format 'v0x0?' if any. Or None
if there isn't a version on the fullname.
"""
|
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 module
(e.g.: pyof.v0x01.common.header)
version (str): The version to be 'inserted' on the module fullname.
Returns:
str: module fullname
The new module fullname, with the replaced version,
|
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 its class
and the module where the class was defined.
If the module is a "python-openflow version specific module" (starts
with "pyof.v0"), then we will get it's version and if it is different
from the 'new_version', then we will get the module on the
'new_version', look for the 'obj' class on the new module and return
an instance of the new version of the 'obj'.
Example:
>>> from pyof.foundation.base import MetaStruct as ms
>>> from pyof.v0x01.common.header import Header
>>> name = 'header'
>>> obj = Header()
>>> new_version = 'v0x04'
>>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version)
>>> header
'header'
>>> obj.version
UBInt8(1)
>>> obj2.version
UBInt8(4)
Args:
name (str): the name of the class attribute being handled.
obj (object): the class attribute itself
new_version (string): the pyof version in which you want the object
'obj'.
Return:
(str, obj): Tuple with class name and object instance.
A tuple in which the first item is the name of the class
attribute (the same that was passed), and the second item is a
instance of the passed class attribute. If the class attribute
is not a pyof versioned attribute, then the same passed object
is returned without any changes. Also, if the obj is a pyof
versioned attribute, but it is already on
|
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):
|
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 the
attributes order are a strong requirement.) For the same reason, this
lib will not work on python versions earlier than 3.6.
.. code-block:: python3
for name, value in self.get_class_attributes():
print("attribute name: {}".format(name))
print("attribute type: {}".format(value))
|
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(_value))
Returns:
|
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: {}".format(class_attribute))
Returns:
|
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:
|
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.
Returns:
int: Total number of bytes used by the struct.
Raises:
Exception: If the struct is not valid.
"""
if value is None:
return sum(cls_val.get_size(obj_val) for obj_val,
|
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 switch,
here we also call :meth:`update_header_length`.
.. seealso:: This method call its parent's :meth:`GenericStruct.pack`
after :meth:`update_header_length`.
Returns:
bytes: A binary data thats represents the Message.
Raises:
Exception: If there
|
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():
|
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.
"""
if field in [None, 'wildcards'] or isinstance(value, Pad):
return
default_value = getattr(Match, field)
if isinstance(default_value, IPAddress):
if field == 'nw_dst':
shift = FlowWildCards.OFPFW_NW_DST_SHIFT
base_mask = FlowWildCards.OFPFW_NW_DST_MASK
else:
shift = FlowWildCards.OFPFW_NW_SRC_SHIFT
base_mask = FlowWildCards.OFPFW_NW_SRC_MASK
# First we clear the nw_dst/nw_src mask related bits on the current
# wildcard by setting 0 on all of them while we keep all other bits
# as they are.
self.wildcards &= FlowWildCards.OFPFW_ALL ^ base_mask
# nw_dst and nw_src wildcard fields have 6 bits each.
# "base_mask" is the 'all ones' for
|
python
|
{
"resource": ""
}
|
q3234
|
ActionSetField.pack
|
train
|
def pack(self, value=None):
"""Pack this structure updating the length and padding it."""
self._update_length()
|
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
|
python
|
{
"resource": ""
}
|
q3236
|
VLAN._validate
|
train
|
def _validate(self):
"""Assure this is a valid VLAN header instance."""
if self.tpid.value
|
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'),
|
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.pack()
output += self.value.pack()
return output
elif isinstance(value, type(self)):
|
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.
"""
|
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) + source_list[1]
source_lower = (source_list[2] << 8) + source_list[3]
destination_upper = (destination_list[0] << 8) + destination_list[1]
destination_lower = (destination_list[2] << 8) + destination_list[3]
block_sum = ((self._version_ihl << 8 | self._dscp_ecn) + self.length +
self.identification + self._flags_offset +
|
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.
"""
|
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)
|
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(packet)
version = packet[0]
try:
pyof_lib
|
python
|
{
"resource": ""
}
|
q3244
|
ErrorMsg.unpack
|
train
|
def unpack(self, buff, offset=0):
"""Unpack binary data into python object."""
|
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)
|
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):
|
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(bgColor)
|
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 _TimeoutException: # not found,
|
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, columnIndex):
return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex)
elif columnIndex > 0 and \
|
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.
|
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
|
python
|
{
"resource": ""
}
|
q3252
|
SyntaxHighlighter.isComment
|
train
|
def isComment(self, block, column):
"""Check if character at column is a comment
"""
dataObject = block.userData()
data
|
python
|
{
"resource": ""
}
|
q3253
|
SyntaxHighlighter.isBlockComment
|
train
|
def isBlockComment(self, block, column):
"""Check if character at column is a block comment
"""
dataObject = block.userData()
|
python
|
{
"resource": ""
}
|
q3254
|
SyntaxHighlighter.isHereDoc
|
train
|
def isHereDoc(self, block, column):
"""Check if character at column is a here document
"""
dataObject = block.userData()
|
python
|
{
"resource": ""
}
|
q3255
|
Lines._atomicModification
|
train
|
def _atomicModification(func):
"""Decorator
Make document modification atomic
"""
def wrapper(*args, **kwargs):
self = args[0]
|
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
|
python
|
{
"resource": ""
}
|
q3257
|
Lines.append
|
train
|
def append(self, text):
"""Append line to the end
"""
cursor = QTextCursor(self._doc)
|
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(text)
cursor.insertBlock()
elif index
|
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.
"""
|
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._isBlockContinuing(prevBlock)) or \
|
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":
|
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.
"""
|
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.widget is None else options.widget.style()
doc = QTextDocument()
doc.setDocumentMargin(1)
doc.setHtml(options.text)
if options.widget is not None:
doc.setDefaultFont(options.widget.font())
# bad long (multiline) strings processing doc.setTextWidth(options.rect.width())
options.text = ""
style.drawControl(QStyle.CE_ItemViewItem, options, painter);
ctx = QAbstractTextDocumentLayout.PaintContext()
# Highlighting text if item is selected
if option.state & QStyle.State_Selected:
|
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 \
|
python
|
{
"resource": ""
}
|
q3265
|
RectangularSelection.delete
|
train
|
def delete(self):
"""Del or Backspace pressed. Delete selection"""
with self._qpart:
for cursor in self.cursors():
|
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 \
|
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._qpart.cursorPosition[1])
self._start = (line, visibleColumn)
modifiersWithoutAltShift = keyEvent.modifiers() & ( ~ (Qt.AltModifier | Qt.ShiftModifier))
newEvent = QKeyEvent(keyEvent.type(),
keyEvent.key(),
modifiersWithoutAltShift,
keyEvent.text(),
keyEvent.isAutoRepeat(),
|
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
|
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 == 0:
return 0
elif not '\t' in text:
return visiblePos
else:
|
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 - currentLine) > self._MAX_SIZE or \
abs(startVisibleCol - currentCol) > self._MAX_SIZE:
# Too big rectangular selection freezes the GUI
self._qpart.userWarning.emit('Rectangular selection area is too big')
self._start = None
return []
currentBlockText = self._qpart.textCursor().block().text()
currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol)
for lineNumber in range(min(startLine, currentLine),
max(startLine, currentLine) + 1):
block = self._qpart.document().findBlockByNumber(lineNumber)
cursor = QTextCursor(block)
realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol)
realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol)
|
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)
for cursor in cursors:
selection =
|
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()])
|
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()
|
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
|
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(mimeData.data(self.MIME_TYPE)).decode('utf8')
lines = text.splitlines()
cursorLine, cursorCol = self._qpart.cursorPosition
if cursorLine + len(lines) > len(self._qpart.lines):
for i in range(cursorLine + len(lines) - len(self._qpart.lines)):
self._qpart.lines.append('')
with self._qpart:
for
|
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
margins = self._qpart.getMargins()
occupiedRanges = []
for margin in margins:
bitRange = margin.getBitRange()
if bitRange is not None:
# pick the right position
added = False
for index in range( len( occupiedRanges ) ):
r = occupiedRanges[ index ]
if bitRange[ 1 ] < r[ 0 ]:
occupiedRanges.insert(index, bitRange)
|
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 height not added to rect, last line number sometimes is not drawn
blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height()
|
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:
raise Exception( "The margin '" + self._name +
"' must be a positive integer" )
if value >= 2 ** self._bit_count:
raise Exception( "The margin '" + self._name +
|
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 +
"' did not allocate any bits for the values")
val = block.userState()
if val in [ 0, -1 ]:
|
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():
|
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.path.join(os.path.dirname(__file__), "data", "xml", xmlFileName)
|
python
|
{
"resource": ""
}
|
q3282
|
SyntaxManager._getSyntaxByLanguageName
|
train
|
def _getSyntaxByLanguageName(self, syntaxName):
"""Get syntax by its name. Name is defined in the xml file
"""
|
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
|
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:
|
python
|
{
"resource": ""
}
|
q3285
|
ContextStack.append
|
train
|
def append(self, context, data):
"""Returns new context, which contains current stack and new frame
"""
|
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):
|
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 \
(not textToMatchObject.isWordStart):
return None
#Special case. If pattern starts with ^ - check column number manually
if self.lineStart and \
textToMatchObject.currentColumnIndex > 0:
return None
if self.dynamic:
string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData)
|
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.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser
string = string.replace('[:digit:]', '\\d')
|
python
|
{
"resource": ""
}
|
q3290
|
AbstractNumberRule._countDigits
|
train
|
def _countDigits(self, text):
"""Count digits at start of text
"""
index = 0
while index < len(text):
|
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 None:
contextStack = prevContextStack
else:
contextStack = self._defaultContextStack
highlightedSegments = []
lineContinue = False
currentColumnIndex = 0
textTypeMap = []
if len(text) > 0:
while currentColumnIndex < len(text):
_logger.debug('In context %s', contextStack.currentContext().name)
length, newContextStack, segments, textTypeMapPart, lineContinue = \
contextStack.currentContext().parseBlock(contextStack, currentColumnIndex, text)
highlightedSegments += segments
contextStack = newContextStack
textTypeMap += textTypeMapPart
currentColumnIndex += length
if not lineContinue:
while contextStack.currentContext().lineEndContext is not None:
oldStack = contextStack
|
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, '{')
|
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()):
return None
for block in self.iterateBlocksBackFrom(block.previous()):
text = block.text()
if re.match(r"^\s*(default\s*|case\b.*):", text):
dbg("trySwitchStatement: success in line %d" % block.blockNumber())
return
|
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 and not autoIndent:
indent = self.tryCppComment(block)
if indent is None:
indent = self.trySwitchStatement(block)
if indent is None:
indent = self.tryAccessModifiers(block)
if indent is None:
indent = self.tryBrace(block)
|
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:
|
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 \
|
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]
if text.endswith(')'):
|
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, ' ' for 4 space symbols
"""
indenterName = indenterName.lower()
if indenterName in ('haskell', 'lilypond'): # not supported yet
logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName)
from qutepart.indenter.base import IndentAlgNormal as indenterClass
elif 'none' == indenterName:
from qutepart.indenter.base import IndentAlgBase as indenterClass
elif 'normal' == indenterName:
from qutepart.indenter.base import IndentAlgNormal as indenterClass
elif 'cstyle' == indenterName:
from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass
elif 'python' == indenterName:
from qutepart.indenter.python import IndentAlgPython as indenterClass
elif 'ruby'
|
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]
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.