text
stringlengths
0
1.05M
meta
dict
# $Id: Module.py,v 1.3 2017/09/06 03:03:58 tyamamot Exp $ import re, sys from Instance import * from Pin import * from settings import * class Module: def __init__(self, line): self.name = line.split(" ")[1] self.module_line = line.split(" ")[1:] self.instances = {} # input/output pin list. List of class Pin #self.inputs = [] #self.outputs = [] # input/output pin list. List of class Pin indexed by pin name self.inputs = {} self.outputs = {} def get_pins_of_line(self, line, str): index = line.find(str) return line[index+len(str):].replace(" ","").replace(";","").split(",") def add_inputs(self,line): for i in self.get_pins_of_line(line, settings.tag_input): #print "add_inputs():", i self.inputs[i] = Pin(i, self, settings.tag_input) self.inputs[i].set_is_external_pin() def add_outputs(self,line): for i in self.get_pins_of_line(line, settings.tag_output): #self.outputs.append( Pin(i, self, settings.tag_output)) self.outputs[i] = Pin(i, self, "output") self.outputs[i].set_is_external_pin() def add_library_inputs(self,line): for i in self.get_pins_of_line(line, settings.tag_input): #print "add_inputs():", i self.inputs[i] = Pin(i, self, settings.tag_input) def add_library_outputs(self,line): for i in self.get_pins_of_line(line, settings.tag_output): #self.outputs.append( Pin(i, self, settings.tag_output)) self.outputs[i] = Pin(i, self, settings.tag_output) def add_inouts(self,line): self.inouts.append( self.get_pins_of_line(line, "inout") ) def add_instance(self,line): remove_space = line.strip(" ") module_end_index = remove_space.find(" ") my_module_name = remove_space[:module_end_index] remaining_line = remove_space[module_end_index:].replace(" ","") inst_end_index = remaining_line.find("(",module_end_index+1) inst_name = remaining_line[:inst_end_index] #print "add_instance: inst=", inst_name, "module=",my_module_name , ",parent module=",self.name self.instances[inst_name] = Instance( self, inst_name, my_module_name, remaining_line[inst_end_index+1:].replace(";","").replace(" ","").replace("\t","")[:-1]) def input_count(self): return len(self.inputs) def output_count(self): return len(self.outputs) def report_name(self): print "name=", self.name def report_inputs(self): for i in self.inputs: print i def report_outputs(self): for i in self.outputs: print i def report_inouts(self): n=0 for i in self.inouts: print n, i n += 1 def report_instances(self): n=0 print "#instances =", len(self.instances) for i in self.instances: print n, i.report() n += 1 def find_instance(self, instance_name, this_module=""): inst = None inst_index = instance_name.find(".") if inst_index >=0: this_instance_name = instance_name[:inst_index] else: this_instance_name = instance_name if this_module=="": this_module = settings.current_design if this_module.instances.has_key(this_instance_name): #print " ", this_instance_name, "found in ", this_module.name inst = this_module.instances[ this_instance_name ] if inst_index >= 0: next_instance_name = instance_name[inst_index+1:] #print "next_instance_name = ", next_instance_name , " in ", inst.module_name next_module = settings.my_design.find_module_by_name( inst.module_name ) if next_module != "": #print "call find_instance(). inst=", next_instance_name, ",module=", inst.module_name inst = next_module.find_instance( next_instance_name, next_module ) #else: #print "No such module: ", inst.module_name elif this_module.outputs.has_key(this_instance_name) : inst = this_module.outputs[ this_instance_name ] elif this_module.inputs.has_key(this_instance_name) : inst = this_module.inputs[ this_instance_name ] else: print "find_instance(): not found", instance_name return inst def is_input(self, pinname): ans = False for i in self.inputs: if i == pinname: ans = True break return ans def is_output(self, pinname): ans = False for i in self.outputs: if i == pinname: ans = True break return ans def get_input(self, ith): return self.inputs[ith] def get_output(self, ith): return self.outputs[ith]
{ "repo_name": "tyamamot5/Verilog-netlist-viewer", "path": "Module.py", "copies": "1", "size": "5083", "license": "apache-2.0", "hash": -2977560448193724400, "line_mean": 33.3445945946, "line_max": 167, "alpha_frac": 0.5551839465, "autogenerated": false, "ratio": 3.6940406976744184, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47492246441744185, "avg_score": null, "num_lines": null }
# $Id: //modules/xmlrpclib/selftest.py#5 $ # minimal xmlrpclib selftest (2.1 and later) import xmlrpclib, string def roundtrip(data): """ Make sure the given data survives a marshal/unmarshal roundtrip >>> roundtrip((1,)) >>> roundtrip((1L,)) >>> roundtrip(("1",)) >>> roundtrip(([], [])) >>> roundtrip(((), ())) # @XMLRPC11 ([], []) >>> roundtrip(({"one": 1, "two": 2},)) >>> roundtrip(({},)) >>> roundtrip((xmlrpclib.DateTime(0), xmlrpclib.True, xmlrpclib.False)) >>> roundtrip((xmlrpclib.Binary("data"),)) >>> roundtrip(xmlrpclib.Fault(100, "cans of spam")) Traceback (most recent call last): Fault: <Fault 100: 'cans of spam'> >>> roundtrip(("hello", xmlrpclib.Binary("test"), 1, 2.0, [3, 4, 5])) """ body = xmlrpclib.dumps(data) result = xmlrpclib.loads(body)[0] if result != data: print result def request_encoding(data, method, encoding=None): r""" Test http request marshalling >>> request_encoding(unicode("abc", "ascii"), "test", "iso-8859-1") (((u'abc',), 'test'), (('abc',), 'test')) >>> request_encoding(unicode("åäö", "iso-8859-1"), "test", "iso-8859-1") (((u'\xe5\xe4\xf6',), 'test'), ((u'\xe5\xe4\xf6',), 'test')) >>> request_encoding(unicode("åäö", "iso-8859-1"), "test") (((u'\xe5\xe4\xf6',), 'test'), ((u'\xe5\xe4\xf6',), 'test')) """ if not isinstance(data, type(())): data = (data,) body = xmlrpclib.dumps(data, method, encoding=encoding) return (data, method), xmlrpclib.loads(body) if __name__ == "__main__": import doctest, selftest doctest.testmod(selftest)
{ "repo_name": "HuaweiSNC/OPS2", "path": "src/python/xmlrpclib_1_0_1/selftest.py", "copies": "1", "size": "1643", "license": "mit", "hash": -3948107326539617000, "line_mean": 31.86, "line_max": 76, "alpha_frac": 0.5709068777, "autogenerated": false, "ratio": 3.2470355731225298, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43179424508225295, "avg_score": null, "num_lines": null }
# $Id: //modules/xmlrpclib/selftest.py#5 $ # minimal xmlrpclib selftest (2.1 and later) import xmlrpclib, string def roundtrip(data): """ Make sure the given data survives a marshal/unmarshal roundtrip >>> roundtrip((1,)) >>> roundtrip((1L,)) >>> roundtrip(("1",)) >>> roundtrip(([], [])) >>> roundtrip(((), ())) # @XMLRPC11 ([], []) >>> roundtrip(({"one": 1, "two": 2},)) >>> roundtrip(({},)) >>> roundtrip((xmlrpclib.DateTime(0), xmlrpclib.True, xmlrpclib.False)) >>> roundtrip((xmlrpclib.Binary("data"),)) >>> roundtrip(xmlrpclib.Fault(100, "cans of spam")) Traceback (most recent call last): Fault: <Fault 100: 'cans of spam'> >>> roundtrip(("hello", xmlrpclib.Binary("test"), 1, 2.0, [3, 4, 5])) """ body = xmlrpclib.dumps(data) result = xmlrpclib.loads(body)[0] if result != data: print result def request_encoding(data, method, encoding=None): r""" Test http request marshalling >>> request_encoding(unicode("abc", "ascii"), "test", "iso-8859-1") (((u'abc',), 'test'), (('abc',), 'test')) >>> request_encoding(unicode("åäö", "iso-8859-1"), "test", "iso-8859-1") (((u'\xe5\xe4\xf6',), 'test'), ((u'\xe5\xe4\xf6',), 'test')) >>> request_encoding(unicode("åäö", "iso-8859-1"), "test") (((u'\xe5\xe4\xf6',), 'test'), ((u'\xe5\xe4\xf6',), 'test')) """ if not isinstance(data, type(())): data = (data,) body = xmlrpclib.dumps(data, method, encoding=encoding) return (data, method), xmlrpclib.loads(body) if __name__ == "__main__": import doctest, selftest doctest.testmod(selftest)
{ "repo_name": "Yinxiaoli/iros2015_folding", "path": "src/folding_control/src/xmlrpclib-1.0.1/selftest.py", "copies": "1", "size": "1693", "license": "mit", "hash": -4225847033256891000, "line_mean": 31.86, "line_max": 76, "alpha_frac": 0.5540460721, "autogenerated": false, "ratio": 3.339250493096647, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.93760771179772, "avg_score": 0.003443889443889444, "num_lines": 50 }
# "Copyright (c) 2000-2003 The Regents of the University of California. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written agreement # is hereby granted, provided that the above copyright notice, the following # two paragraphs and the author appear in all copies of this software. # # IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT # OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY # OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS # ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO # PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." # @author Cory Sharp <cssharp@eecs.berkeley.edu> import sys, os, string from jpype import jimport, JObject def openMoteIF(sourceName) : tinyos = jimport.net.tinyos messenger = JObject( None, tinyos.util.Messenger ) source = tinyos.packet.BuildSource.makePhoenix( sourceName, messenger ) source.setPacketErrorHandler( jimport.PyPhoenixError(source) ) moteif = tinyos.message.MoteIF( source ) if source.isAlive() : moteif.start() else : raise RuntimeError, "could not open MoteIF %s" % sourceName return moteif class MoteIFCache(object) : def __init__(self) : self._active = {} def get(self,source) : if self.isAlive(source) : return self._active[source] sys.stderr.write( "get MoteIF for %s\n" % source ) self._active[source] = openMoteIF( "serial@%s:telos" % source ) return self._active[source] def isAlive(self,source) : if self.has(source) : if self._active[source].getSource().isAlive() : return True return False def has(self,source) : if self._active.has_key(source) : return True return False
{ "repo_name": "ekiwi/tinyos-1.x", "path": "contrib/nestfe/python/pytos/MoteIF.py", "copies": "2", "size": "2230", "license": "bsd-3-clause", "hash": 5880945245105777000, "line_mean": 32.2835820896, "line_max": 77, "alpha_frac": 0.730941704, "autogenerated": false, "ratio": 3.303703703703704, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9775893926093642, "avg_score": 0.0517502963220125, "num_lines": 67 }
# $Id: mrt.py 29 2007-01-26 02:29:07Z jon.oberheide $ # -*- coding: utf-8 -*- """Multi-threaded Routing Toolkit.""" from __future__ import absolute_import from . import dpkt from . import bgp # Multi-threaded Routing Toolkit # http://www.ietf.org/internet-drafts/draft-ietf-grow-mrt-03.txt # MRT Types NULL = 0 START = 1 DIE = 2 I_AM_DEAD = 3 PEER_DOWN = 4 BGP = 5 # Deprecated by BGP4MP RIP = 6 IDRP = 7 RIPNG = 8 BGP4PLUS = 9 # Deprecated by BGP4MP BGP4PLUS_01 = 10 # Deprecated by BGP4MP OSPF = 11 TABLE_DUMP = 12 BGP4MP = 16 BGP4MP_ET = 17 ISIS = 32 ISIS_ET = 33 OSPF_ET = 64 # BGP4MP Subtypes BGP4MP_STATE_CHANGE = 0 BGP4MP_MESSAGE = 1 BGP4MP_ENTRY = 2 BGP4MP_SNAPSHOT = 3 BGP4MP_MESSAGE_32BIT_AS = 4 # Address Family Types AFI_IPv4 = 1 AFI_IPv6 = 2 class MRTHeader(dpkt.Packet): __hdr__ = ( ('ts', 'I', 0), ('type', 'H', 0), ('subtype', 'H', 0), ('len', 'I', 0) ) class TableDump(dpkt.Packet): __hdr__ = ( ('view', 'H', 0), ('seq', 'H', 0), ('prefix', 'I', 0), ('prefix_len', 'B', 0), ('status', 'B', 1), ('originated_ts', 'I', 0), ('peer_ip', 'I', 0), ('peer_as', 'H', 0), ('attr_len', 'H', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) plen = self.attr_len l = [] while plen > 0: attr = bgp.BGP.Update.Attribute(self.data) self.data = self.data[len(attr):] plen -= len(attr) l.append(attr) self.attributes = l class BGP4MPMessage(dpkt.Packet): __hdr__ = ( ('src_as', 'H', 0), ('dst_as', 'H', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) ) class BGP4MPMessage_32(dpkt.Packet): __hdr__ = ( ('src_as', 'I', 0), ('dst_as', 'I', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) )
{ "repo_name": "dimagol/trex-core", "path": "scripts/external_libs/dpkt-1.9.1/dpkt/mrt.py", "copies": "3", "size": "2018", "license": "apache-2.0", "hash": 5578432291937465000, "line_mean": 19.8041237113, "line_max": 64, "alpha_frac": 0.4945490585, "autogenerated": false, "ratio": 2.7014725568942435, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46960216153942436, "avg_score": null, "num_lines": null }
# $Id: mrt.py 29 2007-01-26 02:29:07Z jon.oberheide $ # -*- coding: utf-8 -*- """Multi-threaded Routing Toolkit.""" import dpkt import bgp import struct # Multi-threaded Routing Toolkit # http://www.ietf.org/internet-drafts/draft-ietf-grow-mrt-03.txt # MRT Types NULL = 0 START = 1 DIE = 2 I_AM_DEAD = 3 PEER_DOWN = 4 BGP = 5 # Deprecated by BGP4MP RIP = 6 IDRP = 7 RIPNG = 8 BGP4PLUS = 9 # Deprecated by BGP4MP BGP4PLUS_01 = 10 # Deprecated by BGP4MP OSPF = 11 TABLE_DUMP = 12 TABLE_DUMP_V2 = 13 BGP4MP = 16 BGP4MP_ET = 17 ISIS = 32 ISIS_ET = 33 OSPFv3 = 48 OSPFv3_ET = 49 OSPF_ET = 64 # BGP4MP Subtypes BGP4MP_STATE_CHANGE = 0 BGP4MP_MESSAGE = 1 BGP4MP_ENTRY = 2 BGP4MP_SNAPSHOT = 3 BGP4MP_MESSAGE_32BIT_AS = 4 # Address Family Types AFI_IPv4 = 1 AFI_IPv6 = 2 # TABLE_DUMP_V2 Subtypes PEER_INDEX_TABLE = 1 RIB_IPV4_UNICAST = 2 RIB_IPV4_MULTICAST = 3 RIB_IPV6_UNICAST = 4 RIB_IPV6_MULTICAST = 5 RIB_GENERIC = 6 class MRTHeader(dpkt.Packet): __hdr__ = ( ('ts', 'I', 0), ('type', 'H', 0), ('subtype', 'H', 0), ('len', 'I', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) class TableDump(dpkt.Packet): __hdr__ = ( ('view', 'H', 0), ('seq', 'H', 0), ('prefix', 'I', 0), ('prefix_len', 'B', 0), ('status', 'B', 1), ('originated_ts', 'I', 0), ('peer_ip', 'I', 0), ('peer_as', 'H', 0), ('attr_len', 'H', 0) ) def __init__(self, *arg, **kwargs): super(TableDump, self).__init__(arg, kwargs) def unpack(self, buf): dpkt.Packet.unpack(self, buf) plen = self.attr_len l = [] while plen > 0: attr = bgp.BGP.Update.Attribute(self.data) self.data = self.data[len(attr):] plen -= len(attr) l.append(attr) self.data = self.attributes = l def __str__(self): return self.pack_hdr() + struct.pack('>H', sum(map(len, self.attributes))) + \ ''.join(map(str, self.attributes)) class TableDumpV2(dpkt.Packet): __hdr__ = ( ('seq', 'I', 0), ('prefix_len', 'B', 0), # ('prefix', 'I', 0), # ('entry_count', 'H', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) self.prefix_len = (self.prefix_len + 7) / 8 tmp = self.data[:self.prefix_len] tmp += (4 - len(tmp)) * '\x00' self.prefix = tmp self.data = self.data[self.prefix_len:] self.entry_count = struct.unpack('>H', self.data[:2])[0] self.data = self.data[2:] e = [] for _ in range(self.entry_count): entry = self.RIBIPv4(self.data) e.append(entry) self.data = self.data[len(entry):] self.data = self.entries = e def __len__(self): return self.__hdr_len__ + sum(map(len, self.entries)) # class PeerIndexTable(dpkt.Packet): # __hdr__ = ( # ('collector_bgp_id', 'I', 0), # ('view_name_len', 'H', 0), # # ('view_name', 's', 0), # # ('peer_count', 'H', 0), # ) # def unpack(self, buf): # dpkt.Packet.unpack(self, buf) # self.view_name = self.data[:self.view_name_len] # self.data = self.data[self.view_name_len] # self.peer_count = struct.unpack('>H', self.data[:2]) # self.data = self.data[2:] # peers = [] # plen = self.peer_count # while plen > 0: # peer = self.PeerEntry(self.data) # self.data = self.data[len(peer):] # plen -= len(peer) # peers.append(peer) # self.peers = peers # def __len__(self): # return self.__hdr_len__ + \ # 2 + len(self.view_name) + \ # 2 + sum(map(len, self.peers)) # class PeerEntry(dpkt.Packet): # pass class RIBIPv4(dpkt.Packet): __hdr__ = ( ('peer', 'H', 0), ('orig_ts', 'I', 0), ('attr_len', 'H', 0), ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) plen = self.attr_len l = [] while plen > 0: attr = bgp.BGP.Update.Attribute(self.data) self.data = self.data[len(attr):] plen -= len(attr) l.append(attr) self.attributes = l def __len__(self): return self.__hdr_len__ + sum(map(len, self.attributes)) class BGP4MPMessage(dpkt.Packet): __hdr__ = ( ('src_as', 'H', 0), ('dst_as', 'H', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) ) class BGP4MPMessage_32(dpkt.Packet): __hdr__ = ( ('src_as', 'I', 0), ('dst_as', 'I', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) )
{ "repo_name": "jack8daniels2/dpkt", "path": "dpkt/mrt.py", "copies": "1", "size": "5037", "license": "bsd-3-clause", "hash": -5298554033432286000, "line_mean": 25.3717277487, "line_max": 86, "alpha_frac": 0.4792535239, "autogenerated": false, "ratio": 2.969929245283019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3949182769183019, "avg_score": null, "num_lines": null }
# $Id: mrt.py 29 2007-01-26 02:29:07Z jon.oberheide $ # -*- coding: utf-8 -*- """Multi-threaded Routing Toolkit.""" import dpkt import bgp # Multi-threaded Routing Toolkit # http://www.ietf.org/internet-drafts/draft-ietf-grow-mrt-03.txt # MRT Types NULL = 0 START = 1 DIE = 2 I_AM_DEAD = 3 PEER_DOWN = 4 BGP = 5 # Deprecated by BGP4MP RIP = 6 IDRP = 7 RIPNG = 8 BGP4PLUS = 9 # Deprecated by BGP4MP BGP4PLUS_01 = 10 # Deprecated by BGP4MP OSPF = 11 TABLE_DUMP = 12 BGP4MP = 16 BGP4MP_ET = 17 ISIS = 32 ISIS_ET = 33 OSPF_ET = 64 # BGP4MP Subtypes BGP4MP_STATE_CHANGE = 0 BGP4MP_MESSAGE = 1 BGP4MP_ENTRY = 2 BGP4MP_SNAPSHOT = 3 BGP4MP_MESSAGE_32BIT_AS = 4 # Address Family Types AFI_IPv4 = 1 AFI_IPv6 = 2 class MRTHeader(dpkt.Packet): __hdr__ = ( ('ts', 'I', 0), ('type', 'H', 0), ('subtype', 'H', 0), ('len', 'I', 0) ) class TableDump(dpkt.Packet): __hdr__ = ( ('view', 'H', 0), ('seq', 'H', 0), ('prefix', 'I', 0), ('prefix_len', 'B', 0), ('status', 'B', 1), ('originated_ts', 'I', 0), ('peer_ip', 'I', 0), ('peer_as', 'H', 0), ('attr_len', 'H', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) plen = self.attr_len l = [] while plen > 0: attr = bgp.BGP.Update.Attribute(self.data) self.data = self.data[len(attr):] plen -= len(attr) l.append(attr) self.attributes = l class BGP4MPMessage(dpkt.Packet): __hdr__ = ( ('src_as', 'H', 0), ('dst_as', 'H', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) ) class BGP4MPMessage_32(dpkt.Packet): __hdr__ = ( ('src_as', 'I', 0), ('dst_as', 'I', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) )
{ "repo_name": "hexcap/dpkt", "path": "dpkt/mrt.py", "copies": "5", "size": "1965", "license": "bsd-3-clause", "hash": 4662202836246866000, "line_mean": 19.46875, "line_max": 64, "alpha_frac": 0.4885496183, "autogenerated": false, "ratio": 2.6771117166212535, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0006944444444444445, "num_lines": 96 }
# $Id: mrt.py 29 2007-01-26 02:29:07Z jon.oberheide $ """Multi-threaded Routing Toolkit.""" import dpkt import bgp # Multi-threaded Routing Toolkit # http://www.ietf.org/internet-drafts/draft-ietf-grow-mrt-03.txt # MRT Types NULL = 0 START = 1 DIE = 2 I_AM_DEAD = 3 PEER_DOWN = 4 BGP = 5 # Deprecated by BGP4MP RIP = 6 IDRP = 7 RIPNG = 8 BGP4PLUS = 9 # Deprecated by BGP4MP BGP4PLUS_01 = 10 # Deprecated by BGP4MP OSPF = 11 TABLE_DUMP = 12 BGP4MP = 16 BGP4MP_ET = 17 ISIS = 32 ISIS_ET = 33 OSPF_ET = 64 # BGP4MP Subtypes BGP4MP_STATE_CHANGE = 0 BGP4MP_MESSAGE = 1 BGP4MP_ENTRY = 2 BGP4MP_SNAPSHOT = 3 BGP4MP_MESSAGE_32BIT_AS = 4 # Address Family Types AFI_IPv4 = 1 AFI_IPv6 = 2 class MRTHeader(dpkt.Packet): __hdr__ = ( ('ts', 'I', 0), ('type', 'H', 0), ('subtype', 'H', 0), ('len', 'I', 0) ) class TableDump(dpkt.Packet): __hdr__ = ( ('view', 'H', 0), ('seq', 'H', 0), ('prefix', 'I', 0), ('prefix_len', 'B', 0), ('status', 'B', 1), ('originated_ts', 'I', 0), ('peer_ip', 'I', 0), ('peer_as', 'H', 0), ('attr_len', 'H', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) plen = self.attr_len l = [] while plen > 0: attr = bgp.BGP.Update.Attribute(self.data) self.data = self.data[len(attr):] plen -= len(attr) l.append(attr) self.attributes = l class BGP4MPMessage(dpkt.Packet): __hdr__ = ( ('src_as', 'H', 0), ('dst_as', 'H', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) ) class BGP4MPMessage_32(dpkt.Packet): __hdr__ = ( ('src_as', 'I', 0), ('dst_as', 'I', 0), ('intf', 'H', 0), ('family', 'H', AFI_IPv4), ('src_ip', 'I', 0), ('dst_ip', 'I', 0) )
{ "repo_name": "ashrith/dpkt", "path": "dpkt/mrt.py", "copies": "15", "size": "1986", "license": "bsd-3-clause", "hash": -6928588478149755000, "line_mean": 20.5869565217, "line_max": 64, "alpha_frac": 0.4783484391, "autogenerated": false, "ratio": 2.565891472868217, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
# $Id: MurckoScaffold.py 3672 2010-06-14 17:10:00Z landrgr1 $ # # Created by Peter Gedeck, September 2008 # """ Generation of Murcko scaffolds from a molecule """ from rdkit import Chem from rdkit.Chem import AllChem murckoTransforms = [AllChem.ReactionFromSmarts('[*:1]-[!#1;D1]>>[*:1][H]'), AllChem.ReactionFromSmarts('[*:1]-[!#1;D2]#[AD1]>>[*:1][H]'), AllChem.ReactionFromSmarts('[*:1]-[!#1;D2]=[AD1]>>[*:1][H]'), AllChem.ReactionFromSmarts('[*:1]-[!#1;D3](=[AD1])=[AD1]>>[*:1][H]')] def MakeScaffoldGeneric(mol): """ Makes a Murcko scaffold generic (i.e. all atom types->C and all bonds ->single >>> Chem.MolToSmiles(MakeScaffoldGeneric(Chem.MolFromSmiles('c1ccccc1'))) 'C1CCCCC1' >>> Chem.MolToSmiles(MakeScaffoldGeneric(Chem.MolFromSmiles('c1ncccc1'))) 'C1CCCCC1' The following were associated with sf.net issue 246 >>> Chem.MolToSmiles(MakeScaffoldGeneric(Chem.MolFromSmiles('c1[nH]ccc1'))) 'C1CCCC1' >>> Chem.MolToSmiles(MakeScaffoldGeneric(Chem.MolFromSmiles('C1[NH2+]C1'))) 'C1CC1' >>> Chem.MolToSmiles(MakeScaffoldGeneric(Chem.MolFromSmiles('C1[C@](Cl)(F)O1'))) 'CC1(C)CC1' """ res = Chem.Mol(mol) for atom in res.GetAtoms(): if atom.GetAtomicNum() != 1: atom.SetAtomicNum(6) atom.SetIsAromatic(False) atom.SetFormalCharge(0) atom.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED) atom.SetNoImplicit(0) atom.SetNumExplicitHs(0) for bond in res.GetBonds(): bond.SetBondType(Chem.BondType.SINGLE) bond.SetIsAromatic(False) return Chem.RemoveHs(res) murckoPatts = ['[!#1;D3;$([D3]-[!#1])](=[AD1])=[AD1]', '[!#1;D2;$([D2]-[!#1])]=,#[AD1]', '[!#1;D1;$([D1]-[!#1;!n])]'] murckoQ = '[' + ','.join(['$(%s)' % x for x in murckoPatts]) + ']' murckoQ = Chem.MolFromSmarts(murckoQ) murckoPatts = [Chem.MolFromSmarts(x) for x in murckoPatts] aromaticNTransform = AllChem.ReactionFromSmarts('[n:1]-[D1]>>[nH:1]') def GetScaffoldForMol(mol): """ Return molecule object containing scaffold of mol >>> m = Chem.MolFromSmiles('Cc1ccccc1') >>> GetScaffoldForMol(m) <rdkit.Chem.rdchem.Mol object at 0x...> >>> Chem.MolToSmiles(GetScaffoldForMol(m)) 'c1ccccc1' >>> m = Chem.MolFromSmiles('Cc1cc(Oc2nccc(CCC)c2)ccc1') >>> Chem.MolToSmiles(GetScaffoldForMol(m)) 'c1ccc(Oc2ccccn2)cc1' """ if 1: # pylint: disable=using-constant-test res = Chem.MurckoDecompose(mol) res.ClearComputedProps() res.UpdatePropertyCache() Chem.GetSymmSSSR(res) else: res = _pyGetScaffoldForMol(mol) return res def _pyGetScaffoldForMol(mol): while mol.HasSubstructMatch(murckoQ): for patt in murckoPatts: mol = Chem.DeleteSubstructs(mol, patt) for atom in mol.GetAtoms(): if atom.GetAtomicNum() == 6 and atom.GetNoImplicit() and atom.GetExplicitValence() < 4: atom.SetNoImplicit(False) h = Chem.MolFromSmiles('[H]') mol = Chem.ReplaceSubstructs(mol, Chem.MolFromSmarts('[D1;$([D1]-n)]'), h, True)[0] mol = Chem.RemoveHs(mol) return mol def MurckoScaffoldSmiles(smiles=None, mol=None, includeChirality=False): """ Returns MurckScaffold Smiles from smiles >>> MurckoScaffoldSmiles('Cc1cc(Oc2nccc(CCC)c2)ccc1') 'c1ccc(Oc2ccccn2)cc1' >>> MurckoScaffoldSmiles(mol=Chem.MolFromSmiles('Cc1cc(Oc2nccc(CCC)c2)ccc1')) 'c1ccc(Oc2ccccn2)cc1' """ if smiles: mol = Chem.MolFromSmiles(smiles) if mol is None: raise ValueError('No molecule provided') scaffold = GetScaffoldForMol(mol) if not scaffold: return None # pragma: nocover return Chem.MolToSmiles(scaffold, includeChirality) def MurckoScaffoldSmilesFromSmiles(smiles, includeChirality=False): """ Returns MurckScaffold Smiles from smiles >>> MurckoScaffoldSmilesFromSmiles('Cc1cc(Oc2nccc(CCC)c2)ccc1') 'c1ccc(Oc2ccccn2)cc1' """ return MurckoScaffoldSmiles(smiles=smiles, includeChirality=includeChirality) #------------------------------------ # # doctest boilerplate # def _runDoctests(verbose=None): # pragma: nocover import sys import doctest failed, _ = doctest.testmod(optionflags=doctest.ELLIPSIS, verbose=verbose) sys.exit(failed) if __name__ == '__main__': # pragma: nocover _runDoctests()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Scaffolds/MurckoScaffold.py", "copies": "1", "size": "4215", "license": "bsd-3-clause", "hash": -7029800277970723000, "line_mean": 29.7664233577, "line_max": 91, "alpha_frac": 0.6730723606, "autogenerated": false, "ratio": 2.5607533414337786, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37338257020337784, "avg_score": null, "num_lines": null }
# @(#) $Id: NameTree.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $ __revision__ = "$Id: NameTree.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $" ''' TODO: - missing lots of inline doc here - ??? ''' from Acspy.Util.ACSCorba import nameService from Acspy.Util import NodeList import CosNaming import string import sys from traceback import print_exc # # extensions added to the different object types in the name service # extensions = { 'ROProperty':'rop', 'RWProperty':'rwp', 'Device':'dev', 'Service':'srv' } # # getnode - used by many local routines to resolve and narrow # the node and return a context. # def getnode (node, wd): ctx = None try: obj = wd.resolve(node) try: ctx = obj._narrow(CosNaming.NamingContext) except: ctx = None except: pass return ctx # # keep a directory tree without any cycles # class nameTree(object): def __init__(self, corba_object, nameServerName=''): # get reference to name service ns_obj = nameService() if (ns_obj is None): print "name service bad resolve" return self.top = ns_obj._narrow(CosNaming.NamingContext) self.path = [('',self.top)] # keep track of where we are self.pathcopy = [] # # ls () # def ls (self): # pragma: NO COVER (n, cwd) = self.path[-1] nl = NodeList.nodeList(cwd) nl.ls() # # listdir () # def listdir (self): # pragma: NO COVER (n, cwd) = self.path[-1] nl = NodeList.nodeList(cwd) return nl.listdir() # # mkdir (path) # def mkdir (self, path): # # path can be relative or absolute. This is determined # by the leading / # # break path into parts by the / # nodes = string.splitfields(path,'/') wd = None if (nodes[0] == ''): wd = self.top del nodes[0] else: (n, wd) = self.path[-1] for name in nodes: # try to resolve the name, if it fails, jump out and # start creating contexts node = [CosNaming.NameComponent (name,"")] nextwd = getnode (node , wd) if (nextwd is None): try: nextwd = wd.bind_new_context (node) # except: print "Error binding new context for ", name, "!!!", sys.exc_info()[0] return wd = nextwd # # cd (path) # def cd (self, path, ignore_error=0): nodes = string.splitfields(path,'/') # check for "../../xxx" addresses if (nodes[0] == '..'): while (nodes != [] and self.path != [] and nodes[0] == '..'): (x,y) = self.path[len(self.path)-1] if(x == '/'): break del nodes[0] del self.path[len(self.path)-1] # reached the directory top, fix self.path if ((nodes != [] and nodes[0] == '') or len(self.path) == 0): # absolute, search from the top self.path = [('', self.top)] (n, wd) = self.path[len(self.path)-1] changed = 1 changes = [] for name in nodes: if (name == ''): continue wd = getnode ([CosNaming.NameComponent (name,"")], wd) if (wd is not None): changes.append ((name, wd)) continue if (ignore_error == 0): changed = 0 return 0 if (changed == 1): self.path = self.path + changes return 1 # # getObject (name, type) - return CORBA::Object() # def getObject (self, name, type): "this does not handle absolute or relative path, just cwd" (n, cwd) = self.path[-1] leaf = [CosNaming.NameComponent (name, type)] try: return cwd.resolve (leaf) except CosNaming.NamingContext.NotFound: raise except: print 'name service error resolving ', self.path, name, type print sys.exc_info() # # putObject (name, object) - put CORBA::Object() at this # name. If name does not exist, make it. If no object, then # make a placeholder # def putObject (self, name, type, object): # pragma: NO COVER "this does not handle absolute or relative path, just cwd" # first just try a rebind() if that fails, then see if # path and name. If it is a path, then check the path # and make it if needed. Then try a bind. (n, cwd) = self.path[-1] leaf = [CosNaming.NameComponent (name, type)] return cwd.rebind (leaf, object) # # putObject (name, object) - put CORBA::Object() at this # name. If name does not exist, make it. If no object, then # make a placeholder # def delObject (self, name, type): # pragma: NO COVER "this does not handle absolute or relative path, just cwd" # Unbind something. (n, cwd) = self.path[-1] leaf = [CosNaming.NameComponent (name, type)] cwd.unbind (leaf) return # # pwd() # def pwd (self): wd = '' for (x, y) in self.path: if x == '': continue wd = wd + '/' + x return wd # # rm() # def rm (self, name, args="noforce"): # pragma: NO COVER # pushd this directory, cd to other directory less last name, # get the objet for last name, and if it is a context, check # force flag. if it is to go, follow the directory tree and # toss all the links if (args == "noforce"): return return # # cp() # def cp (self, name): # pragma: NO COVER return # # pushd() # def pushd (self, l=""): # pragma: NO COVER if (l == "?"): i = 0 for path in self.pathcopy: s = '' for (n, ctx) in path: s = s + '/' + n print "%02d: %s" %(i, s) i = i + 1 else: self.pathcopy.append(self.path) return # # popd() # def popd (self, index=-1): # pragma: NO COVER try: self.path = self.pathcopy.pop(index) except: print "top of list, no pop" return if (__name__ == "__main__"): # pragma: NO COVER print '==> Testing nameTree class' testlevel = 0 nt = nameTree(None) print '==> Naming service variable name is: nt' print '==> Listing entries in Naming Service:' nt.ls () # It seems this does not work print '==> PWD: ', nt.pwd () if (testlevel > 0): nt.pushd () nt.cd ("/") nt.pushd () nt.cd ("/cat") nt.pushd() nt.pushd ("?") print '==> cd into MOUNT1.0' # Nothing happens here nt.cd("MOUNT1.0") nt.ls () # nt.cd("Antenna Systems/Services/Cryogenics") # obj = nt.getObject("Status","rwp") # from acs.baci import ESO # status = obj._narrow(ESO.ROlong) # print 'status at status'
{ "repo_name": "csrg-utfsm/acscb", "path": "LGPL/CommonSoftware/acspycommon/src/Acspy/Util/NameTree.py", "copies": "3", "size": "6447", "license": "mit", "hash": -4831142977122012000, "line_mean": 22.4436363636, "line_max": 80, "alpha_frac": 0.5712734605, "autogenerated": false, "ratio": 3.2511346444780633, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5322408104978064, "avg_score": null, "num_lines": null }
""" Textbox subclass for easier text manipulation, this module defines the following class: - `Command`: `Textbox` subclass. Improved word traversal. How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``>>> import command_``. 2. Initialize command: ``>>> mycommand = command_.Command(...)``. 3. Interact with command:: a) Print command description: ``mycommand.print_description()``. b) Move cursor: ``mycommand.get_input_field().move(0, 0)``. c) Edit command in-place: ``mycommand.edit()``. """ __docformat__ = 'reStructuredText' import curses from curses import textpad import difflib import re import sre_constants import subprocess import bindings class Command(textpad.Textbox): """ `Textbox` subclass with methods for smooth text editing. Command contains methods for simpler text formatting and string manipulation. Implemented standard - EMACS(?) shortcuts for word traversal and editing. - ALT_B: Back, left one word. - ALT_F: Forward, right one word. - CTRL_A: Beginning of the line (Home). - CTRL_B: Back one character. - CTRL_D: Delete. - CTRL_E: End of the line (End). - CTRL_F: Forward one character. - CTRL_H: Backspace. - CTRL_K: Cut line after cursor to clipboard. - CTRL_U: Cut line before cursor to clipboard. - CTRL_W: Cut word before cursor to clipboard. - CTRL_Y: Yank (paste). DSUSP, delayed suspend on BSD-based systems. - TAB: Cycle through command arguments. - SHIFT_TAB: Reverse cycle through command arguments. """ # TODO: Remove this debug hack. stdscr = None """Global, main terminal screen.""" def __init__(self, item, box, input_field, tab_offset, *args, **kwargs): """ Extend `Textbox` `__init__` method. Initialize a `Command` object. Parameters: - `item`: a dictionary containing command, description, tags. - `box`: - `_line_number`: Number of row command is rendered in terminal. - `_y_offset`: _y_ offset from left terminal screen edge. - `_xmax`: Maximum screen size, _x_ axis. - `input_field`: edible window (one line). - `tab_offset`: Number of characters tab characters to show. """ self._item = item self._line_number, self._y_offset, self._xmax = box self._input_field = input_field self._tab_offset = tab_offset self._tab_value = {} """Dictionary of indexes of words (arguments) that are tabbable. Key is index of position in input field, value is word.""" self._tab_args = {} """Dictionary of words (arguments), that are tabbable. Key is the word, value is a list of starting indexes of that word.""" self._index_tab = [] """Indexes of edible arguments (_x_ axis).""" self._shadow_command = '' self._prev_ch = '' """Previous character. Used for navigation hacks.""" self._selected_word = '' """Currently marked argument.""" self._edible_mask = '' """Mask that explains how command is formatted. Similar to printf.""" self._yank = '' """Holds content of cut string to paste.""" self._center = False """Center for tab arguments.""" self._right_edge = self._xmax - self._y_offset """_x_ position of right edge.""" self._curr_offset = 0 """Relative _x_ offset.""" if 'nix_edit' in self._item: self._shadow_command = self._format_command( self._item['nix_edit']['mask'], self._item['nix_edit']['args'] ) else: self._shadow_command = self._item['command'] self._print_command(self._shadow_command) textpad.Textbox.__init__(self, *args, **kwargs) def do_command(self, ch): """Extend `Textbox` `do_command` method.""" cy, cx = self._input_field.getyx() """Cursor position within this line.""" if ch in bindings.edit_term: # Termination keys. Leave input_field. Mark prev cursor position? return 0 if self._prev_ch is bindings.ESC: if ch is bindings.ESC: # Leaving input on double ESC. return 0 elif ch in (bindings.ALT_KEYS): if ch is bindings.KEY_B: _s = self._prev_word(cx) self._input_field.move(0, _s) elif ch is bindings.KEY_F: _s = self._next_word(cx) self._input_field.move(0, _s) self._adjust_index_tab() return self._super_return(1, 0) #else: Treat the rest as _prev_ch was not ESC key. Ignore or cont? if ch is bindings.ESC: return self._super_return(1, ch) if ch in bindings.tabs: # Move cursor to the next nearest tab field. if ch is bindings.TAB: selected_word_index, next_field = self._find_next_field( cx, self._index_tab ) else: selected_word_index, next_field = self._find_prev_field( cx, self._index_tab ) try: self._selected_word = self._tab_value[next_field] except KeyError: self._selected_word = '' next_field = cx self._input_field.move(0, next_field) self._center = True # TODO: Mark current word. #self._mark_word(cx, self._selected_word) return self._super_return( textpad.Textbox.do_command(self, ch), ch) if ch in bindings.moving: return self._super_return( textpad.Textbox.do_command(self, ch), 0) if ch in bindings.editing: return self._super_return(self._edit(cx, ch), 0) # Characters from now on considered invasive. _e = cx # End position. Replacing marked word changes that. chr_fail = False clear_word = False insert_char = True if self._prev_ch in bindings.tabs: clear_word = True arg_len = len(self._selected_word) _e = cx + arg_len self._delete_chars(arg_len) if ch is bindings.BACKSLASH: character = '\\\\' _e += 1 elif ch in bindings.backspace: insert_char = False if clear_word: self._shadow_command = (self._shadow_command[:cx - 1] + self._shadow_command[_e - 1:]) self._adjust_index_tab() return self._super_return(1, 0) self._shadow_command = (self._shadow_command[:cx - 1] + self._shadow_command[_e:]) ch = bindings.CTRL_H elif ch in bindings.delete: insert_char = False if clear_word: self._shadow_command = (self._shadow_command[:cx - 1] + self._shadow_command[_e - 1:]) self._adjust_index_tab() return self._super_return(1, 0) self._shadow_command = (self._shadow_command[:cx] + self._shadow_command[_e + 1:]) ch = bindings.CTRL_D elif ch in bindings.yank: self._shadow_command = (self._shadow_command[:cx] + str(self._yank) + self._shadow_command[_e:]) self._put_chars(str(self._yank)) self._adjust_index_tab() return self._super_return(1, 0) else: try: character = chr(ch) except ValueError: chr_fail = True if chr_fail: # We are lost. Read the command from _input_field. ret_val = textpad.Textbox.do_command(self, ch) cy, cx = self._input_field.getyx() self._shadow_command = self._input_field.instr(0, 0) self._input_field.move(0, cx) return self._super_return(ret_val, 0) if insert_char: try: self._shadow_command = (self._shadow_command[:cx] + character + self._shadow_command[_e:]) except UnicodeDecodeError: return self._super_return(1, 0) ret_val = textpad.Textbox.do_command(self, ch) self._adjust_index_tab() return self._super_return(ret_val, 0) def edit(self, validate=None): "Edit in the widget window and collect the results." while 1: ch = self.win.getch() if validate: ch = validate(ch) if not ch: continue if not self.do_command(ch): break cy, cx = self._input_field.getyx() if cx - self._right_edge > self._curr_offset: self._curr_offset = cx - self._right_edge elif cx < self._curr_offset: self._curr_offset = cx if self._center: self._center = False tab_offset = self._tab_offset if cx - self._curr_offset < self._right_edge: tab_offset = (cx - self._curr_offset - (self._right_edge - tab_offset)) self._curr_offset += tab_offset self.win.refresh(0, self._curr_offset, self._line_number, self._y_offset, self._line_number, self._xmax) return self.gather() def get_command(self): return self._shadow_command def get_input_field(self): """Return input field. Used to control cursor.""" return self._input_field def print_description(self): """Print command description in main terminal window.""" stdscr.move(2, 1) stdscr.clrtoeol() stdscr.addstr(2, 2, self._item['description']) stdscr.refresh() def _adjust_index_tab(self): """ Recalculate new <TAB> indexes for edible arguments. Updates following structures: - `_tab_args` - `_tab_value` - `_index_tab` """ # TODO: Create new tab value for new arguments. #is_changed, prev_arg, start_idx, end_idx = _detect_broken_args() self._index_tab = [] for key, value in self._tab_args.iteritems(): kw = r'\b' + re.escape(key) self._tab_args[key] = [m.start() for m in re.finditer( kw, self._shadow_command)] for pos in self._tab_args[key]: self._tab_value[pos] = key # Compare previous and current tab indexes for a current argument. # This seems buggy and probably is. #self.prev_tab_args[key] self._index_tab = sorted(list(set( self._index_tab + self._tab_args[key]))) def _calculate_new_index_tab(self, prev, curr): """Difference between previous and current command.""" # Difference between two strings in python [1] # [1]: http://stackoverflow.com/questions/1209800/difference-between-two-strings-in-python-php diff = difflib.SequenceMatcher( a=prev, b=curr ) for i, block in enumerate(diff.get_matching_blocks()): nstr = "match at a[%d] and b[%d] of length %d" % block def _clear_input_field(self): """Clear input field.""" self._input_field.move(0, 0) self._input_field.clrtoeol() def _delete_chars(self, count, move_cursor=-1): """Removes n characters from a string.""" ret_val = 1 if move_cursor > -1: self._input_field.move(0, move_cursor) for i in range(count): ret_val = textpad.Textbox.do_command(self, bindings.CTRL_D) return ret_val def _detect_broken_args(self): """ Return tuple: (is_changed, prev_arg, start_idx, end_idx). Return values: - is_changed: True, if edible argument has changed. - prev_arg: Argument that is about to change. - start_idx: Start index of argument. - end_idx: End index of argument. When there is no match, (False, '', -1, -1) is return value. """ # Check, if any of the tabbable arguments is being changed. # Find nearest index_tab c_lo = -1 c_hi = -1 p_lo = -1 p_hi = -1 n_lo = -1 n_hi = -1 is_changed = False prev_arg = '' start_idx = -1 end_idx = -1 cy, cx = self._input_field.getyx() idx, c_lo = self._find_next_field(cx, self._index_tab) if c_lo > -1: # Get tabbable index previous, current and next position. c_hi = c_lo + len(self._tab_value[c_lo]) if idx >= 0 and len(self._index_tab) > 0: # mylist[-1] is ok with python. p_lo = self._index_tab[idx - 1] p_hi = p_lo + len(self._tab_value[p_lo]) if (idx + 1) == len(self._index_tab): # This case covers cyclic-ism. n_lo = self._index_tab[0] n_hi = n_lo + len(self._tab_value[n_lo]) elif (idx + 1) < len(self._index_tab): n_lo = self._index_tab[idx + 1] n_hi = n_lo + len(self._tab_value[n_lo]) # Find if changed occurred on tabbable word. if p_lo <= cx <= p_hi: is_changed = True prev_arg = self._tab_value[p_lo] start_idx = p_lo end_idx = p_hi if c_lo <= cx <= c_hi: is_changed = True prev_arg = self._tab_value[c_lo] start_idx = c_lo end_idx = c_hi if n_lo <= cx <= n_hi: is_changed = True prev_arg = self._tab_value[n_lo] start_idx = n_lo end_idx = n_hi # Figure if word is in tab_args # Figure out changes of that word. # Create new tabbable argument. def _edit(self, cx, ch): """Puts removed characters before / after cursor in yank.""" _s = -1 self._yank = '' if ch is bindings.CTRL_K: self._yank = self._shadow_command[cx:] self._shadow_command = self._shadow_command[:cx] elif ch is bindings.CTRL_U: _s = 0 self._yank = self._shadow_command[:cx] self._shadow_command = self._shadow_command[cx:] elif ch is bindings.CTRL_W: _s = self._prev_word(cx) self._yank = self._shadow_command[_s:cx] self._shadow_command = (self._shadow_command[:_s] + self._shadow_command[cx:]) self._adjust_index_tab() return self._delete_chars(len(self._yank), _s) def _find_next_field(self, cx, tab_field): """Return tuple, index & position of next edible argument on <TAB>.""" if len(tab_field) < 1: return (0, -1) for n, i in enumerate(tab_field): if i > cx: return (n, i) return (0, tab_field[0]) def _find_prev_field(self, cx, tab_field): """Return tuple, index, position of prev edible argument on <STAB>.""" if len(tab_field) < 1: return (0, -1) for n, i in reversed(list(enumerate(tab_field))): if i < cx: return (n, i) return (len(tab_field) - 1, tab_field[-1]) def _format_command(self, command, args): """ Make and return formatted command as string. This is run on initialization. Parameters: - `command`: printf like formatted string. - `args`: tuple of arguments that should be put into formatted string. """ holders = re.split("(%s|%c)", command) tmp_len = 0 j = 0 for i, holder in enumerate(holders): if holder == "%s": holder = args[j] holders[i] = holder if holder not in self._tab_args: self._tab_args[holder] = [] j += 1 elif holder == "%c": holder = subprocess.Popen( args[j], stdout=subprocess.PIPE, shell=True ).stdout.read().strip() holders[i] = holder if holder not in self._tab_args: self._tab_args[holder] = [] j += 1 tmp_len += len(holder) self._shadow_command = ''.join(holders) # Create index_tab self._adjust_index_tab() return ''.join(holders) def _mark_word(self, cx, selected_word): """Invert colors on marked word.""" # Highlighting and selecting text with python curses [2] # [2]: http://stackoverflow.com/questions/6807808/highlighting-and-selecting-text-with-python-curses """ command_field[index].addnstr( 0, next_field, selected_word, len(selected_word), curses.A_REVERSE ) command_field[index].insstr( 0, next_field, selected_word, curses.A_REVERSE ) """ """ command_field[index].chgat( 0, next_field, len(selected_word), curses.A_REVERSE ) """ pass def _next_word(self, cx): """Return starting index of next word.""" p = re.compile(r'\w+\b') _s = [m.start() for m in p.finditer(self._shadow_command, cx)] try: _s = _s[1] except IndexError: _s = len(self._shadow_command) return _s def _prev_word(self, cx): """Return starting index of previous word.""" p = re.compile(r'\w+\b') _s = [m.start() for m in p.finditer(self._shadow_command, 0, cx)] try: _s = _s[-1] except IndexError: _s = 0 return _s def _print_command(self, command): """Print command in the commands list in main terminal window.""" self._input_field.addstr(0, 0, command) self._input_field.refresh(0, 0, self._line_number, self._y_offset, self._line_number, self._xmax) def _put_chars(self, yank): """Inserts n characters in a string.""" for chy in yank: textpad.Textbox.do_command(self, chy) def _reformat_command(self): """Reformats current state of a command to match edible state.""" # Match text inside single and/or double quotes. #re.split(r'''("(?:[^\\"]+|\\.)*")|('(?:[^\\']+|\\.)*')''', nstr) pass def _super_return(self, ret_val, ch): """Only exit point from the graph.""" self._prev_ch = ch return ret_val
{ "repo_name": "shearch/shearch", "path": "src/command_.py", "copies": "1", "size": "19453", "license": "bsd-3-clause", "hash": -8296280585950252000, "line_mean": 32.7140381282, "line_max": 108, "alpha_frac": 0.5147792114, "autogenerated": false, "ratio": 3.9522551808208046, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49670343922208043, "avg_score": null, "num_lines": null }
# $Id: netbios.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Network Basic Input/Output System.""" from __future__ import absolute_import import struct from . import dpkt from . import dns def encode_name(name): """Return the NetBIOS first-level encoded name.""" l = [] for c in struct.pack('16s', name): c = ord(c) l.append(chr((c >> 4) + 0x41)) l.append(chr((c & 0xf) + 0x41)) return ''.join(l) def decode_name(nbname): """Return the NetBIOS first-level decoded nbname.""" if len(nbname) != 32: return nbname l = [] for i in range(0, 32, 2): l.append(chr(((ord(nbname[i]) - 0x41) << 4) | ((ord(nbname[i + 1]) - 0x41) & 0xf))) return ''.join(l).split('\x00', 1)[0] # RR types NS_A = 0x01 # IP address NS_NS = 0x02 # Name Server NS_NULL = 0x0A # NULL NS_NB = 0x20 # NetBIOS general Name Service NS_NBSTAT = 0x21 # NetBIOS NODE STATUS # RR classes NS_IN = 1 # NBSTAT name flags NS_NAME_G = 0x8000 # group name (as opposed to unique) NS_NAME_DRG = 0x1000 # deregister NS_NAME_CNF = 0x0800 # conflict NS_NAME_ACT = 0x0400 # active NS_NAME_PRM = 0x0200 # permanent # NBSTAT service names nbstat_svcs = { # (service, unique): list of ordered (name prefix, service name) tuples (0x00, 0): [('', 'Domain Name')], (0x00, 1): [('IS~', 'IIS'), ('', 'Workstation Service')], (0x01, 0): [('__MSBROWSE__', 'Master Browser')], (0x01, 1): [('', 'Messenger Service')], (0x03, 1): [('', 'Messenger Service')], (0x06, 1): [('', 'RAS Server Service')], (0x1B, 1): [('', 'Domain Master Browser')], (0x1C, 0): [('INet~Services', 'IIS'), ('', 'Domain Controllers')], (0x1D, 1): [('', 'Master Browser')], (0x1E, 0): [('', 'Browser Service Elections')], (0x1F, 1): [('', 'NetDDE Service')], (0x20, 1): [('Forte_$ND800ZA', 'DCA IrmaLan Gateway Server Service'), ('', 'File Server Service')], (0x21, 1): [('', 'RAS Client Service')], (0x22, 1): [('', 'Microsoft Exchange Interchange(MSMail Connector)')], (0x23, 1): [('', 'Microsoft Exchange Store')], (0x24, 1): [('', 'Microsoft Exchange Directory')], (0x2B, 1): [('', 'Lotus Notes Server Service')], (0x2F, 0): [('IRISMULTICAST', 'Lotus Notes')], (0x30, 1): [('', 'Modem Sharing Server Service')], (0x31, 1): [('', 'Modem Sharing Client Service')], (0x33, 0): [('IRISNAMESERVER', 'Lotus Notes')], (0x43, 1): [('', 'SMS Clients Remote Control')], (0x44, 1): [('', 'SMS Administrators Remote Control Tool')], (0x45, 1): [('', 'SMS Clients Remote Chat')], (0x46, 1): [('', 'SMS Clients Remote Transfer')], (0x4C, 1): [('', 'DEC Pathworks TCPIP service on Windows NT')], (0x52, 1): [('', 'DEC Pathworks TCPIP service on Windows NT')], (0x87, 1): [('', 'Microsoft Exchange MTA')], (0x6A, 1): [('', 'Microsoft Exchange IMC')], (0xBE, 1): [('', 'Network Monitor Agent')], (0xBF, 1): [('', 'Network Monitor Application')] } def node_to_service_name(name_service_flags): name, service, flags = name_service_flags try: unique = int(flags & NS_NAME_G == 0) for namepfx, svcname in nbstat_svcs[(service, unique)]: if name.startswith(namepfx): return svcname except KeyError: pass return '' class NS(dns.DNS): """NetBIOS Name Service.""" class Q(dns.DNS.Q): pass class RR(dns.DNS.RR): """NetBIOS resource record.""" def unpack_rdata(self, buf, off): if self.type == NS_A: self.ip = self.rdata elif self.type == NS_NBSTAT: num = ord(self.rdata[0]) off = 1 l = [] for i in range(num): name = self.rdata[off:off + 15].split(None, 1)[0].split('\x00', 1)[0] service = ord(self.rdata[off + 15]) off += 16 flags = struct.unpack('>H', self.rdata[off:off + 2])[0] off += 2 l.append((name, service, flags)) self.nodenames = l # XXX - skip stats def pack_name(self, buf, name): return dns.DNS.pack_name(self, buf, encode_name(name)) def unpack_name(self, buf, off): name, off = dns.DNS.unpack_name(self, buf, off) return decode_name(name), off class Session(dpkt.Packet): """NetBIOS Session Service.""" __hdr__ = ( ('type', 'B', 0), ('flags', 'B', 0), ('len', 'H', 0) ) SSN_MESSAGE = 0 SSN_REQUEST = 1 SSN_POSITIVE = 2 SSN_NEGATIVE = 3 SSN_RETARGET = 4 SSN_KEEPALIVE = 5 class Datagram(dpkt.Packet): """NetBIOS Datagram Service.""" __hdr__ = ( ('type', 'B', 0), ('flags', 'B', 0), ('id', 'H', 0), ('src', 'I', 0), ('sport', 'H', 0), ('len', 'H', 0), ('off', 'H', 0) ) DGRAM_UNIQUE = 0x10 DGRAM_GROUP = 0x11 DGRAM_BROADCAST = 0x12 DGRAM_ERROR = 0x13 DGRAM_QUERY = 0x14 DGRAM_POSITIVE = 0x15 DGRAM_NEGATIVE = 0x16
{ "repo_name": "dimagol/trex-core", "path": "scripts/external_libs/dpkt-1.9.1/dpkt/netbios.py", "copies": "3", "size": "5106", "license": "apache-2.0", "hash": 8902814193257640000, "line_mean": 29.2130177515, "line_max": 89, "alpha_frac": 0.5305522914, "autogenerated": false, "ratio": 3.05748502994012, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5088037321340121, "avg_score": null, "num_lines": null }
# $Id: netbios.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Network Basic Input/Output System.""" import struct import dpkt import dns def encode_name(name): """Return the NetBIOS first-level encoded name.""" l = [] for c in struct.pack('16s', name): c = ord(c) l.append(chr((c >> 4) + 0x41)) l.append(chr((c & 0xf) + 0x41)) return ''.join(l) def decode_name(nbname): """Return the NetBIOS first-level decoded nbname.""" if len(nbname) != 32: return nbname l = [] for i in range(0, 32, 2): l.append(chr(((ord(nbname[i]) - 0x41) << 4) | ((ord(nbname[i + 1]) - 0x41) & 0xf))) return ''.join(l).split('\x00', 1)[0] # RR types NS_A = 0x01 # IP address NS_NS = 0x02 # Name Server NS_NULL = 0x0A # NULL NS_NB = 0x20 # NetBIOS general Name Service NS_NBSTAT = 0x21 # NetBIOS NODE STATUS # RR classes NS_IN = 1 # NBSTAT name flags NS_NAME_G = 0x8000 # group name (as opposed to unique) NS_NAME_DRG = 0x1000 # deregister NS_NAME_CNF = 0x0800 # conflict NS_NAME_ACT = 0x0400 # active NS_NAME_PRM = 0x0200 # permanent # NBSTAT service names nbstat_svcs = { # (service, unique): list of ordered (name prefix, service name) tuples (0x00, 0): [('', 'Domain Name')], (0x00, 1): [('IS~', 'IIS'), ('', 'Workstation Service')], (0x01, 0): [('__MSBROWSE__', 'Master Browser')], (0x01, 1): [('', 'Messenger Service')], (0x03, 1): [('', 'Messenger Service')], (0x06, 1): [('', 'RAS Server Service')], (0x1B, 1): [('', 'Domain Master Browser')], (0x1C, 0): [('INet~Services', 'IIS'), ('', 'Domain Controllers')], (0x1D, 1): [('', 'Master Browser')], (0x1E, 0): [('', 'Browser Service Elections')], (0x1F, 1): [('', 'NetDDE Service')], (0x20, 1): [('Forte_$ND800ZA', 'DCA IrmaLan Gateway Server Service'), ('', 'File Server Service')], (0x21, 1): [('', 'RAS Client Service')], (0x22, 1): [('', 'Microsoft Exchange Interchange(MSMail Connector)')], (0x23, 1): [('', 'Microsoft Exchange Store')], (0x24, 1): [('', 'Microsoft Exchange Directory')], (0x2B, 1): [('', 'Lotus Notes Server Service')], (0x2F, 0): [('IRISMULTICAST', 'Lotus Notes')], (0x30, 1): [('', 'Modem Sharing Server Service')], (0x31, 1): [('', 'Modem Sharing Client Service')], (0x33, 0): [('IRISNAMESERVER', 'Lotus Notes')], (0x43, 1): [('', 'SMS Clients Remote Control')], (0x44, 1): [('', 'SMS Administrators Remote Control Tool')], (0x45, 1): [('', 'SMS Clients Remote Chat')], (0x46, 1): [('', 'SMS Clients Remote Transfer')], (0x4C, 1): [('', 'DEC Pathworks TCPIP service on Windows NT')], (0x52, 1): [('', 'DEC Pathworks TCPIP service on Windows NT')], (0x87, 1): [('', 'Microsoft Exchange MTA')], (0x6A, 1): [('', 'Microsoft Exchange IMC')], (0xBE, 1): [('', 'Network Monitor Agent')], (0xBF, 1): [('', 'Network Monitor Application')] } def node_to_service_name((name, service, flags)): try: unique = int(flags & NS_NAME_G == 0) for namepfx, svcname in nbstat_svcs[(service, unique)]: if name.startswith(namepfx): return svcname except KeyError: pass return '' class NS(dns.DNS): """NetBIOS Name Service.""" class Q(dns.DNS.Q): pass class RR(dns.DNS.RR): """NetBIOS resource record.""" def unpack_rdata(self, buf, off): if self.type == NS_A: self.ip = self.rdata elif self.type == NS_NBSTAT: num = ord(self.rdata[0]) off = 1 l = [] for i in range(num): name = self.rdata[off:off + 15].split(None, 1)[0].split('\x00', 1)[0] service = ord(self.rdata[off + 15]) off += 16 flags = struct.unpack('>H', self.rdata[off:off + 2])[0] off += 2 l.append((name, service, flags)) self.nodenames = l # XXX - skip stats def pack_name(self, buf, name): return dns.DNS.pack_name(self, buf, encode_name(name)) def unpack_name(self, buf, off): name, off = dns.DNS.unpack_name(self, buf, off) return decode_name(name), off class Session(dpkt.Packet): """NetBIOS Session Service.""" __hdr__ = ( ('type', 'B', 0), ('flags', 'B', 0), ('len', 'H', 0) ) SSN_MESSAGE = 0 SSN_REQUEST = 1 SSN_POSITIVE = 2 SSN_NEGATIVE = 3 SSN_RETARGET = 4 SSN_KEEPALIVE = 5 class Datagram(dpkt.Packet): """NetBIOS Datagram Service.""" __hdr__ = ( ('type', 'B', 0), ('flags', 'B', 0), ('id', 'H', 0), ('src', 'I', 0), ('sport', 'H', 0), ('len', 'H', 0), ('off', 'H', 0) ) DGRAM_UNIQUE = 0x10 DGRAM_GROUP = 0x11 DGRAM_BROADCAST = 0x12 DGRAM_ERROR = 0x13 DGRAM_QUERY = 0x14 DGRAM_POSITIVE = 0x15 DGRAM_NEGATIVE = 0x16
{ "repo_name": "bpanneton/dpkt", "path": "dpkt/netbios.py", "copies": "6", "size": "5010", "license": "bsd-3-clause", "hash": 928337984464081800, "line_mean": 29.1807228916, "line_max": 89, "alpha_frac": 0.526746507, "autogenerated": false, "ratio": 3.0474452554744524, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6574191762474453, "avg_score": null, "num_lines": null }
# $Id: netbios.py 23 2006-11-08 15:45:33Z dugsong $ """Network Basic Input/Output System.""" import struct import dpkt, dns def encode_name(name): """Return the NetBIOS first-level encoded name.""" l = [] for c in struct.pack('16s', name): c = ord(c) l.append(chr((c >> 4) + 0x41)) l.append(chr((c & 0xf) + 0x41)) return ''.join(l) def decode_name(nbname): """Return the NetBIOS first-level decoded nbname.""" if len(nbname) != 32: return nbname l = [] for i in range(0, 32, 2): l.append(chr(((ord(nbname[i]) - 0x41) << 4) | ((ord(nbname[i+1]) - 0x41) & 0xf))) return ''.join(l).split('\x00', 1)[0] # RR types NS_A = 0x01 # IP address NS_NS = 0x02 # Name Server NS_NULL = 0x0A # NULL NS_NB = 0x20 # NetBIOS general Name Service NS_NBSTAT = 0x21 # NetBIOS NODE STATUS # RR classes NS_IN = 1 # NBSTAT name flags NS_NAME_G = 0x8000 # group name (as opposed to unique) NS_NAME_DRG = 0x1000 # deregister NS_NAME_CNF = 0x0800 # conflict NS_NAME_ACT = 0x0400 # active NS_NAME_PRM = 0x0200 # permanent # NBSTAT service names nbstat_svcs = { # (service, unique): list of ordered (name prefix, service name) tuples (0x00, 0):[ ('', 'Domain Name') ], (0x00, 1):[ ('IS~', 'IIS'), ('', 'Workstation Service') ], (0x01, 0):[ ('__MSBROWSE__', 'Master Browser') ], (0x01, 1):[ ('', 'Messenger Service') ], (0x03, 1):[ ('', 'Messenger Service') ], (0x06, 1):[ ('', 'RAS Server Service') ], (0x1B, 1):[ ('', 'Domain Master Browser') ], (0x1C, 0):[ ('INet~Services', 'IIS'), ('', 'Domain Controllers') ], (0x1D, 1):[ ('', 'Master Browser') ], (0x1E, 0):[ ('', 'Browser Service Elections') ], (0x1F, 1):[ ('', 'NetDDE Service') ], (0x20, 1):[ ('Forte_$ND800ZA', 'DCA IrmaLan Gateway Server Service'), ('', 'File Server Service') ], (0x21, 1):[ ('', 'RAS Client Service') ], (0x22, 1):[ ('', 'Microsoft Exchange Interchange(MSMail Connector)') ], (0x23, 1):[ ('', 'Microsoft Exchange Store') ], (0x24, 1):[ ('', 'Microsoft Exchange Directory') ], (0x2B, 1):[ ('', 'Lotus Notes Server Service') ], (0x2F, 0):[ ('IRISMULTICAST', 'Lotus Notes') ], (0x30, 1):[ ('', 'Modem Sharing Server Service') ], (0x31, 1):[ ('', 'Modem Sharing Client Service') ], (0x33, 0):[ ('IRISNAMESERVER', 'Lotus Notes') ], (0x43, 1):[ ('', 'SMS Clients Remote Control') ], (0x44, 1):[ ('', 'SMS Administrators Remote Control Tool') ], (0x45, 1):[ ('', 'SMS Clients Remote Chat') ], (0x46, 1):[ ('', 'SMS Clients Remote Transfer') ], (0x4C, 1):[ ('', 'DEC Pathworks TCPIP service on Windows NT') ], (0x52, 1):[ ('', 'DEC Pathworks TCPIP service on Windows NT') ], (0x87, 1):[ ('', 'Microsoft Exchange MTA') ], (0x6A, 1):[ ('', 'Microsoft Exchange IMC') ], (0xBE, 1):[ ('', 'Network Monitor Agent') ], (0xBF, 1):[ ('', 'Network Monitor Application') ] } def node_to_service_name((name, service, flags)): try: unique = int(flags & NS_NAME_G == 0) for namepfx, svcname in nbstat_svcs[(service, unique)]: if name.startswith(namepfx): return svcname except KeyError: pass return '' class NS(dns.DNS): """NetBIOS Name Service.""" class Q(dns.DNS.Q): pass class RR(dns.DNS.RR): """NetBIOS resource record.""" def unpack_rdata(self, buf, off): if self.type == NS_A: self.ip = self.rdata elif self.type == NS_NBSTAT: num = ord(self.rdata[0]) off = 1 l = [] for i in range(num): name = self.rdata[off:off+15].split(None, 1)[0].split('\x00', 1)[0] service = ord(self.rdata[off+15]) off += 16 flags = struct.unpack('>H', self.rdata[off:off+2])[0] off += 2 l.append((name, service, flags)) self.nodenames = l # XXX - skip stats def pack_name(self, buf, name): return dns.DNS.pack_name(self, buf, encode_name(name)) def unpack_name(self, buf, off): name, off = dns.DNS.unpack_name(self, buf, off) return decode_name(name), off class Session(dpkt.Packet): """NetBIOS Session Service.""" __hdr__ = ( ('type', 'B', 0), ('flags', 'B', 0), ('len', 'H', 0) ) SSN_MESSAGE = 0 SSN_REQUEST = 1 SSN_POSITIVE = 2 SSN_NEGATIVE = 3 SSN_RETARGET = 4 SSN_KEEPALIVE = 5 class Datagram(dpkt.Packet): """NetBIOS Datagram Service.""" __hdr__ = ( ('type', 'B', 0), ('flags', 'B', 0), ('id', 'H', 0), ('src', 'I', 0), ('sport', 'H', 0), ('len', 'H', 0), ('off', 'H', 0) ) DGRAM_UNIQUE = 0x10 DGRAM_GROUP = 0x11 DGRAM_BROADCAST = 0x12 DGRAM_ERROR = 0x13 DGRAM_QUERY = 0x14 DGRAM_POSITIVE = 0x15 DGRAM_NEGATIVE = 0x16
{ "repo_name": "guke001/QMarkdowner", "path": "dpkt/netbios.py", "copies": "15", "size": "5008", "license": "mit", "hash": -3659465484502234000, "line_mean": 31.5194805195, "line_max": 87, "alpha_frac": 0.5237619808, "autogenerated": false, "ratio": 2.949352179034158, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
# $Id: NetUtils.py 1047 2009-01-15 14:48:58Z graham $ # # Network utilities # import logging from string import split from Functions import all, formatIntList, formatInt def ipAdrStrToInt( adrStr ): """ Convert a dotted ip address to 32 bit integer. """ adrParts = split( adrStr, ".", 3 ) return (int(adrParts[0]) << 24) + (int(adrParts[1]) << 16) + (int(adrParts[2]) << 8) + int(adrParts[3]) def addBroadcastBits( iAdr, bitCount ): """ iAdr is 32 bit integer bitCount is integer. """ # set the broadcast values for idx in range( 32-bitCount ): iAdr = iAdr | (1 << idx) return iAdr def getBroadcastAddressI( adrStr, bitStr ): """ Returns address as Integer """ # else has netmask part. iAdr = ipAdrStrToInt( adrStr ) # integer address bAdr = addBroadcastBits( iAdr, int( bitStr ) ) return bAdr def getBroadcastAddress( adrStr ): """ Convert an ip address in form nn.nn.nn.nn/bb into its broadcast address format. b/bb is optional and assumes caller knows what they are doing. """ netParts = split( adrStr, "/", 1 ) if ( len(netParts) == 1 ): return adrStr # else has netmask part. # else has netmask part. iAdr = ipAdrStrToInt( netParts[0] ) # integer address bAdr = getBroadcastAddressI( netParts[0], netParts[1] ) return "%i.%i.%i.%i" % ( ((bAdr>>24)&0xFF), ((bAdr>>16)&0xFF), ((bAdr>>8)&0xFF), (bAdr&0xFF) ) # Helper functions for processing IP addresses as lists of int values # (I think this representation will be easier to migrate to also support IPv6 - GK) def parseIpAdrs(ipadrs): """ Parse IP address in dotted decomal form, and return a sequence of 4 numbers """ # Strip of any port and/or netmask bits ipadrs = ipadrs.split('/')[0].split(':')[0] return map(int, ipadrs.split('.')) def parseNetAdrs(netadrs): """ Parse network address specification, returning a pair of: (a) IP address bytes tuple (b) number of '1' bits in netmask """ (ipadrs,maskbits) = netadrs.split('/') return (parseIpAdrs(ipadrs),int(maskbits)) def formatIpAdrs(ipbytes): """ Format IP address string from IP addre4ss bytes """ # return "%d.%d.%d.%d" % ipbytes return formatIntList(ipbytes,".") def formatNetAdrs(ipbytes,maskbits): """ Format network address string from IP address bytes and mask bit count """ return formatIpAdrs(ipbytes)+("/%d" % maskbits) def mkNetMask(ipbytes,maskbits=None): """ Make a network mask value as a sequence of IP address bytes May be called with 1 or 2 arguments: if 1 argument, it is a pair of (netbytes,maskbits) if 2 arguments, the first is just netbytes, and the second is maskbits """ if not maskbits: (ipbytes,maskbits) = ipbytes netmask = [] for b in ipbytes: m = 0 if maskbits >= 8: m = 255 elif maskbits > 0: m = (0, 128, 128+64, 128+64+32, 128+64+32+16, 128+64+32+16+8, 128+64+32+16+8+4, 128+64+32+16+8+4+2)[maskbits] netmask.append(m) maskbits -= 8 return netmask def mkBroadcastAddress(netbytes,maskbits=None): """ Make broadcast address for a given network May be called with 1 or 2 arguments: if 1 argument, it is a pair of (netbytes,maskbits) if 2 arguments, the first is just netbytes, and the secvond is maskbits """ def makeadrbyte(m, a): return (~m | a) & 0xFF if not maskbits: (netbytes,maskbits) = netbytes netmask = mkNetMask(netbytes,maskbits) return map(makeadrbyte, netmask, netbytes) def ipInNetwork(ipbytes, netbytes, maskbits=None): """ Test if IP address is part of given network May be called with 2 or 3 arguments: if 2 arguments, the second is a pair of (netbytes,maskbits) if 3 arguments, the second is just netbytes, and the third is maskbits """ def testadrbyte(m, n, a): return (m & a) == (m & n) if not maskbits: (netbytes,maskbits) = netbytes netmask = mkNetMask(netbytes, maskbits) return all(testadrbyte, netmask, netbytes, ipbytes) def getHostIpsAndMask(): """ Helper function returns list of IP networks connected to the current host. Each value is in the form address/maskbits, e.g. 10.0.0.0/8 """ result = list() from socket import gethostbyname_ex, gethostname try: hosts = gethostbyname_ex( gethostname( ) ) for addr in hosts[2]: # convert to ... byts = parseIpAdrs(addr) if byts[0] >= 192: # class C result.append( "%i.%i.%i.0/24" % (byts[0],byts[1],byts[2]) ) elif byts[0] >= 128: # class B result.append( "%i.%i.0.0/16" % (byts[0],byts[1]) ) else: # class A result.append( "%i.0.0.0/8" % (byts[0]) ) except Exception, ex : _log = logging.getLogger('WebBrickLibs.MiscLib.NetUtils') _log.exception(ex) return result # Helper functions for processing MAC addresses as lists of integers def parseMacAdrs(macadrs): """ Parse Mac address in colon-hexadecimal form, and return a sequence of 6 numbers """ def hex(h): return int(h,16) return map(hex, macadrs.split(':')) def formatMacAdrs(macbytes,sep=":"): """ Format MAC address as colon-separated hexadecimals for webBrick command """ return formatIntList(macbytes, sep, formatInt("%02X")) # test cases def _test(): i = parseIpAdrs("193.123.216.121") x = parseIpAdrs("193.123.216.200") n = parseNetAdrs("193.123.216.64/26") b = mkBroadcastAddress(*n) assert formatIpAdrs(b) == "193.123.216.127" assert ipInNetwork(i,*n) assert ipInNetwork(b,*n) assert not ipInNetwork(x,*n) assert parseMacAdrs("01:34:67:9a:BC:eF") == [1,52,103,154,188,239] assert formatMacAdrs([1,52,103,154,188,239],sep='-') == "01-34-67-9A-BC-EF" _test() # End $Id: NetUtils.py 1047 2009-01-15 14:48:58Z graham $
{ "repo_name": "bhavanaananda/DataStage", "path": "src/AdminUIHandler/MiscLib/NetUtils.py", "copies": "8", "size": "6193", "license": "mit", "hash": -379277511526986400, "line_mean": 30.5969387755, "line_max": 108, "alpha_frac": 0.6106894881, "autogenerated": false, "ratio": 3.2560462670872767, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7866735755187277, "avg_score": null, "num_lines": null }
""" Create a new domain key file which is composed of the following: - A random 50 character cookie - A public key - The corresponding private key """ import os import sys import peloton from peloton.utils.crypto import makeCookie from peloton.utils.crypto import newKey from peloton.utils.crypto import makeKeyAndCookieFile from peloton.utils.structs import FilteredOptionParser from peloton.utils import chop tokenlength = 50 keylength = 512 __VERSION__ = "0.1" def main(): usage = "usage: %prog [options]" # add 'arg1 arg2' etc as required parser = FilteredOptionParser(usage=usage, version="Peloton newkey version %s" % __VERSION__) parser.add_option("--prefix", help="Path to directory containing configuration data, links to services etc. [default: %default]", default=peloton.getPlatformDefaultDir('config')) parser.add_option("-d", "--domain", help="""Specify the domain name for which to create a key [default: %default]""", default="Pelotonica") parser.add_option("-k", "--domainkey", help="""Domain key file [default: %default]""", default="$PREFIX/$DOMAIN.key") parser.add_option("-c", "--console", help="""Send to console instead of file""", action="store_true", default=False) opts, args = parser.parse_args() if opts.console: outfile=None else: outfile = os.path.expanduser(opts.domainkey) f = makeKeyAndCookieFile(outfile, keylength, tokenlength) if opts.console: print f return 0 if __name__ == '__main__': sys.exit(main())
{ "repo_name": "aquamatt/Peloton", "path": "src/tools/newkey.py", "copies": "1", "size": "1906", "license": "bsd-3-clause", "hash": 7995949379822885000, "line_mean": 33.0535714286, "line_max": 121, "alpha_frac": 0.6259181532, "autogenerated": false, "ratio": 4.012631578947368, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01578392207858408, "num_lines": 56 }
# $Id:# import FWCore.ParameterSet.Config as cms process = cms.Process('FILLER') # import of standard configurations process.load('Configuration/StandardSequences/Services_cff') process.load('FWCore/MessageService/MessageLogger_cfi') process.load('Configuration/StandardSequences/GeometryIdeal_cff') process.load('Configuration/StandardSequences/MagneticField_38T_cff') process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff') process.load('Configuration/EventContent/EventContent_cff') process.configurationMetadata = cms.untracked.PSet( version = cms.untracked.string('Mit_014a'), annotation = cms.untracked.string('RECOSIMStartup'), name = cms.untracked.string('BambuProduction') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.options = cms.untracked.PSet( Rethrow = cms.untracked.vstring('ProductNotFound'), fileMode = cms.untracked.string('NOMERGE'), ) # input source process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:/build/bendavid/RECOSIMSummer09/TTbar_Summer09-MC_3XY_V25_preproduction-v1/969AE5D9-DA2B-DF11-931D-001CC4C10E02.root') ) process.source.inputCommands = cms.untracked.vstring("keep *", "drop *_MEtoEDMConverter_*_*", "drop L1GlobalTriggerObjectMapRecord_hltL1GtObjectMap__HLT") # other statements process.GlobalTag.globaltag = 'START38_V12::All' process.add_(cms.Service("ObjectService")) process.load("MitProd.BAMBUSequences.BambuFillRECOSIM_cfi") # set the name for the output file process.MitTreeFiller.TreeWriter.fileName = 'XX-MITDATASET-XX' process.MitTreeFiller.TreeWriter.maxSize = cms.untracked.uint32(1790) process.bambu_step = cms.Path(process.BambuFillRECOSIM) # schedule definition process.schedule = cms.Schedule(process.bambu_step)
{ "repo_name": "cpausmit/Kraken", "path": "filefi/014/startup.py", "copies": "1", "size": "1811", "license": "mit", "hash": 3497872704986014700, "line_mean": 35.9591836735, "line_max": 162, "alpha_frac": 0.7835450028, "autogenerated": false, "ratio": 2.9884488448844886, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9182613484879986, "avg_score": 0.017876072560900652, "num_lines": 49 }
# @(#) $Id: NodeList.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $ __revision__ = "$Id: NodeList.py,v 1.1.1.1 2012/03/07 17:40:45 acaproni Exp $" ''' TODO: - most inline doc is missing ''' # # NamingContext utility # import CosNaming class nodeList(object): def __init__ (self, context): # pragma: NO COVER (self.list, self.it) = context.list(1024) #DWF-changed from 80 def listdir (self): list = [] for binding in self.list: # binding - Name, binding type name = binding.binding_name # sequence of name components, 1 deep type = binding.binding_type if (type == CosNaming.ncontext): # directory list = list + [(name[0].id,1)] elif (name[0].kind == ''): # no .xxx list = list + [(name[0].id,0)] else: list = list + [(name[0].id+"."+name[0].kind,0)] return list def ls (self): # pragma: NO COVER for binding in self.list: # binding - Name, binding type name = binding.binding_name # sequence of name components, 1 deep type = binding.binding_type if (type == CosNaming.ncontext): # directory print name[0].id + "/" elif (name[0].kind == ''): # no .xxx print name[0].id else: print name[0].id + "." + name[0].kind # return the object found. should be a naming context def find (self, name, kind): # pragma: NO COVER for binding in self.list: n = binding.binding_name if ((n[0].id == name) & (n[0].kind == kind)): return binding return None
{ "repo_name": "csrg-utfsm/acscb", "path": "LGPL/CommonSoftware/acspycommon/src/Acspy/Util/NodeList.py", "copies": "3", "size": "1547", "license": "mit", "hash": 347175752832672640, "line_mean": 28.75, "line_max": 78, "alpha_frac": 0.5778926955, "autogenerated": false, "ratio": 3.2028985507246377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5280791246224638, "avg_score": null, "num_lines": null }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import warnings from types import IntType, SliceType, StringType, UnicodeType, \ TupleType, ListType, ClassType, TypeType from UserString import UserString # ============================== # Functional Node Base Classes # ============================== class Node: """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return 1 def __str__(self): return self.__unicode__().encode('raw_unicode_escape') def __unicode__(self): # Override in subclass. raise NotImplementedError def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return stop except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: if child.walk(visitor): stop = 1 break except SkipSiblings: pass except StopTraversal: stop = 1 return stop def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ call_depart = 1 stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return stop except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: if child.walkabout(visitor): stop = 1 break except SkipSiblings: pass except SkipChildren: pass except StopTraversal: stop = 1 if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) return stop def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ r = [] if ascend: siblings=1 # Check if `condition` is a class (check for TypeType for Python # implementations that use only new-style classes, like PyPy). if isinstance(condition, (ClassType, TypeType)): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None class Text(Node, UserString): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" def __init__(self, data, rawsource=''): UserString.__init__(self, data) self.rawsource = rawsource """The raw text from which this element was constructed.""" def __repr__(self): data = repr(self.data) if len(data) > 70: data = repr(self.data[:64] + ' ...') return '<%s: %s>' % (self.tagname, data) def __len__(self): return len(self.data) def shortrepr(self): data = repr(self.data) if len(data) > 20: data = repr(self.data[:16] + ' ...') return '<%s: %s>' % (self.tagname, data) def _dom_node(self, domroot): return domroot.createTextNode(self.data) def astext(self): return self.data def __unicode__(self): return self.data def copy(self): return self.__class__(self.data) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.data.splitlines(): result.append(indent + line + '\n') return ''.join(result) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, ListType): value = ' '.join([serial_escape('%s' % v) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([unicode(c) for c in self.children]), self.endtag()) else: return self.emptytag() def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, ListType): values = [serial_escape('%s' % v) for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __getitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): return self.attributes[key] elif isinstance(key, IntType): return self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, UnicodeType) or isinstance(key, StringType): self.attributes[str(key)] = item elif isinstance(key, IntType): self.setup_child(item) self.children[key] = item elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): del self.attributes[key] elif isinstance(key, IntType): del self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return self.attributes.has_key(attr) def delattr(self, attr): if self.attributes.has_key(attr): del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(**self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def __getstate__(self): """ Return dict with unpicklable references removed. """ state = self.__dict__.copy() state['reporter'] = None state['transformer'] = None return state def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if self.ids.has_key(id) and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and not self.ids.has_key(id): break else: id = '' while not id or self.ids.has_key(id): id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if self.nameids.has_key(name): self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if node.has_key('refuri'): refuri = node['refuri'] if old_node['names'] \ and old_node.has_key('refuri') \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return self.nameids.has_key(name) # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if self.substitution_defs.has_key(name): msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, ListType) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass class StopTraversal(TreePruningException): """ Stop the traversal alltogether. The current node's ``depart_...`` method is not affected. The parent nodes ``depart_...`` methods are also called as usual. No other nodes are visited. This is an alternative to NodeFound that does not cause exception handling to trickle up to the caller. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = _non_id_chars.sub('-', ' '.join(string.lower().split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "PatrickKennedy/Sybil", "path": "docutils/nodes.py", "copies": "2", "size": "60239", "license": "bsd-2-clause", "hash": 7451813651599731000, "line_mean": 32.4289678135, "line_max": 79, "alpha_frac": 0.5927721244, "autogenerated": false, "ratio": 4.241884374339835, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002329254582921944, "num_lines": 1801 }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import warnings import types import unicodedata # ============================== # Functional Node Base Classes # ============================== class Node(object): """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return True if sys.version_info < (3,): # on 2.x, str(node) will be a byte string with Unicode # characters > 255 escaped; on 3.x this is no longer necessary def __str__(self): return unicode(self).encode('raw_unicode_escape') def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return stop except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: if child.walk(visitor): stop = 1 break except SkipSiblings: pass except StopTraversal: stop = 1 return stop def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ call_depart = 1 stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return stop except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: if child.walkabout(visitor): stop = 1 break except SkipSiblings: pass except SkipChildren: pass except StopTraversal: stop = 1 if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) return stop def _fast_traverse(self, cls): """Specialized traverse() that only supports instance checks.""" result = [] if isinstance(self, cls): result.append(self) for child in self.children: result.extend(child._fast_traverse(cls)) return result def _all_traverse(self): """Specialized traverse() that doesn't check for a condition.""" result = [] result.append(self) for child in self.children: result.extend(child._all_traverse()) return result def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ if ascend: siblings=1 # Check for special argument combinations that allow using an # optimized version of traverse() if include_self and descend and not siblings: if condition is None: return self._all_traverse() elif isinstance(condition, (types.ClassType, type)): return self._fast_traverse(condition) # Check if `condition` is a class (check for TypeType for Python # implementations that use only new-style classes, like PyPy). if isinstance(condition, (types.ClassType, type)): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) r = [] if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None if sys.version_info < (3,): class reprunicode(unicode): """ A class that removes the initial u from unicode's repr. """ def __repr__(self): return unicode.__repr__(self)[1:] else: reprunicode = unicode class Text(Node, reprunicode): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" if sys.version_info > (3,): def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" if isinstance(data, bytes): raise TypeError('expecting str data, not bytes') return reprunicode.__new__(cls, data) else: def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" return reprunicode.__new__(cls, data) def __init__(self, data, rawsource=''): self.rawsource = rawsource """The raw text from which this element was constructed.""" def __repr__(self): data = reprunicode.__repr__(self) if len(data) > 70: data = reprunicode.__repr__(self[:64] + ' ...') return '<%s: %s>' % (self.tagname, data) def shortrepr(self): data = reprunicode.__repr__(self) if len(data) > 20: data = reprunicode.__repr__(self[:16] + ' ...') return '<%s: %s>' % (self.tagname, data) def _dom_node(self, domroot): return domroot.createTextNode(unicode(self)) def astext(self): return reprunicode(self) # Note about __unicode__: The implementation of __unicode__ here, # and the one raising NotImplemented in the superclass Node had # to be removed when changing Text to a subclass of unicode instead # of UserString, since there is no way to delegate the __unicode__ # call to the superclass unicode: # unicode itself does not have __unicode__ method to delegate to # and calling unicode(self) or unicode.__new__ directly creates # an infinite loop def copy(self): return self.__class__(reprunicode(self), rawsource=self.rawsource) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.splitlines(): result.append(indent + line + '\n') return ''.join(result) # rstrip and lstrip are used by substitution definitions where # they are expected to return a Text instance, this was formerly # taken care of by UserString. Note that then and now the # rawsource member is lost. def rstrip(self, chars=None): return self.__class__(reprunicode.rstrip(self, chars)) def lstrip(self, chars=None): return self.__class__(reprunicode.lstrip(self, chars)) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, list): value = ' '.join([serial_escape('%s' % v) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([unicode(c) for c in self.children]), self.endtag()) else: return self.emptytag() if sys.version_info > (3,): # 2to3 doesn't convert __unicode__ to __str__ __str__ = __unicode__ def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, list): values = [serial_escape('%s' % v) for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __contains__(self, key): # support both membership test for children and attributes # (has_key is translated to "in" by 2to3) if isinstance(key, basestring): return key in self.attributes return key in self.children def __getitem__(self, key): if isinstance(key, basestring): return self.attributes[key] elif isinstance(key, int): return self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, basestring): self.attributes[str(key)] = item elif isinstance(key, int): self.setup_child(item) self.children[key] = item elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, basestring): del self.attributes[key] elif isinstance(key, int): del self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return attr in self.attributes def delattr(self, attr): if attr in self.attributes: del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr # support operator in __contains__ = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(**self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def __getstate__(self): """ Return dict with unpicklable references removed. """ state = self.__dict__.copy() state['reporter'] = None state['transformer'] = None return state def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if id in self.ids and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and id not in self.ids: break else: id = '' while not id or id in self.ids: id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if name in self.nameids: self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if 'refuri' in node: refuri = node['refuri'] if old_node['names'] \ and 'refuri' in old_node \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return name in self.nameids # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if name in self.substitution_defs: msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, list) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass class StopTraversal(TreePruningException): """ Stop the traversal alltogether. The current node's ``depart_...`` method is not affected. The parent nodes ``depart_...`` methods are also called as usual. No other nodes are visited. This is an alternative to NodeFound that does not cause exception handling to trickle up to the caller. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = string.lower() if not isinstance(id, unicode): id = id.decode() id = id.translate(_non_id_translate_digraphs) id = id.translate(_non_id_translate) # get rid of non-ascii characters id = unicodedata.normalize('NFKD', id).\ encode('ASCII', 'ignore').decode('ASCII') # shrink runs of whitespace and replace by hyphen id = _non_id_chars.sub('-', ' '.join(id.split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') _non_id_translate = { 0x00f8: u'o', # o with stroke 0x0111: u'd', # d with stroke 0x0127: u'h', # h with stroke 0x0131: u'i', # dotless i 0x0142: u'l', # l with stroke 0x0167: u't', # t with stroke 0x0180: u'b', # b with stroke 0x0183: u'b', # b with topbar 0x0188: u'c', # c with hook 0x018c: u'd', # d with topbar 0x0192: u'f', # f with hook 0x0199: u'k', # k with hook 0x019a: u'l', # l with bar 0x019e: u'n', # n with long right leg 0x01a5: u'p', # p with hook 0x01ab: u't', # t with palatal hook 0x01ad: u't', # t with hook 0x01b4: u'y', # y with hook 0x01b6: u'z', # z with stroke 0x01e5: u'g', # g with stroke 0x0225: u'z', # z with hook 0x0234: u'l', # l with curl 0x0235: u'n', # n with curl 0x0236: u't', # t with curl 0x0237: u'j', # dotless j 0x023c: u'c', # c with stroke 0x023f: u's', # s with swash tail 0x0240: u'z', # z with swash tail 0x0247: u'e', # e with stroke 0x0249: u'j', # j with stroke 0x024b: u'q', # q with hook tail 0x024d: u'r', # r with stroke 0x024f: u'y', # y with stroke } _non_id_translate_digraphs = { 0x00df: u'sz', # ligature sz 0x00e6: u'ae', # ae 0x0153: u'oe', # ligature oe 0x0238: u'db', # db digraph 0x0239: u'qp', # qp digraph } def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "rimbalinux/LMD3", "path": "docutils/nodes.py", "copies": "2", "size": "66826", "license": "bsd-3-clause", "hash": 8759068132292633000, "line_mean": 32.7695109261, "line_max": 79, "alpha_frac": 0.5738335378, "autogenerated": false, "ratio": 4.2713966123362095, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.584523015013621, "avg_score": null, "num_lines": null }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import re import sys import types import unicodedata import warnings # ============================== # Functional Node Base Classes # ============================== class Node(object): """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return True if sys.version_info < (3,): # on 2.x, str(node) will be a byte string with Unicode # characters > 255 escaped; on 3.x this is no longer necessary def __str__(self): return unicode(self).encode('raw_unicode_escape') def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return stop except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: if child.walk(visitor): stop = 1 break except SkipSiblings: pass except StopTraversal: stop = 1 return stop def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ call_depart = 1 stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return stop except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: if child.walkabout(visitor): stop = 1 break except SkipSiblings: pass except SkipChildren: pass except StopTraversal: stop = 1 if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) return stop def _fast_traverse(self, cls): """Specialized traverse() that only supports instance checks.""" result = [] if isinstance(self, cls): result.append(self) for child in self.children: result.extend(child._fast_traverse(cls)) return result def _all_traverse(self): """Specialized traverse() that doesn't check for a condition.""" result = [] result.append(self) for child in self.children: result.extend(child._all_traverse()) return result def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ if ascend: siblings=1 # Check for special argument combinations that allow using an # optimized version of traverse() if include_self and descend and not siblings: if condition is None: return self._all_traverse() elif isinstance(condition, (types.ClassType, type)): return self._fast_traverse(condition) # Check if `condition` is a class (check for TypeType for Python # implementations that use only new-style classes, like PyPy). if isinstance(condition, (types.ClassType, type)): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) r = [] if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None if sys.version_info < (3,): class reprunicode(unicode): """ A class that removes the initial u from unicode's repr. """ def __repr__(self): return unicode.__repr__(self)[1:] else: reprunicode = unicode class Text(Node, reprunicode): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" if sys.version_info > (3,): def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" if isinstance(data, bytes): raise TypeError('expecting str data, not bytes') return reprunicode.__new__(cls, data) else: def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" return reprunicode.__new__(cls, data) def __init__(self, data, rawsource=''): self.rawsource = rawsource """The raw text from which this element was constructed.""" def shortrepr(self, maxlen=18): data = self if len(data) > maxlen: data = data[:maxlen-4] + ' ...' return '<%s: %s>' % (self.tagname, repr(reprunicode(data))) def __repr__(self): return self.shortrepr(maxlen=68) def _dom_node(self, domroot): return domroot.createTextNode(unicode(self)) def astext(self): return reprunicode(self) # Note about __unicode__: The implementation of __unicode__ here, # and the one raising NotImplemented in the superclass Node had # to be removed when changing Text to a subclass of unicode instead # of UserString, since there is no way to delegate the __unicode__ # call to the superclass unicode: # unicode itself does not have __unicode__ method to delegate to # and calling unicode(self) or unicode.__new__ directly creates # an infinite loop def copy(self): return self.__class__(reprunicode(self), rawsource=self.rawsource) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.splitlines(): result.append(indent + line + '\n') return ''.join(result) # rstrip and lstrip are used by substitution definitions where # they are expected to return a Text instance, this was formerly # taken care of by UserString. Note that then and now the # rawsource member is lost. def rstrip(self, chars=None): return self.__class__(reprunicode.rstrip(self, chars)) def lstrip(self, chars=None): return self.__class__(reprunicode.lstrip(self, chars)) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, list): value = ' '.join([serial_escape('%s' % v) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([unicode(c) for c in self.children]), self.endtag()) else: return self.emptytag() if sys.version_info > (3,): # 2to3 doesn't convert __unicode__ to __str__ __str__ = __unicode__ def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, list): values = [serial_escape('%s' % v) for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __contains__(self, key): # support both membership test for children and attributes # (has_key is translated to "in" by 2to3) if isinstance(key, basestring): return key in self.attributes return key in self.children def __getitem__(self, key): if isinstance(key, basestring): return self.attributes[key] elif isinstance(key, int): return self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, basestring): self.attributes[str(key)] = item elif isinstance(key, int): self.setup_child(item) self.children[key] = item elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, basestring): del self.attributes[key] elif isinstance(key, int): del self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return attr in self.attributes def delattr(self, attr): if attr in self.attributes: del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr # support operator in __contains__ = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(rawsource=self.rawsource, **self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def __getstate__(self): """ Return dict with unpicklable references removed. """ state = self.__dict__.copy() state['reporter'] = None state['transformer'] = None return state def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if id in self.ids and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and id not in self.ids: break else: id = '' while not id or id in self.ids: id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if name in self.nameids: self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if 'refuri' in node: refuri = node['refuri'] if old_node['names'] \ and 'refuri' in old_node \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return name in self.nameids # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if name in self.substitution_defs: msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, list) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass class StopTraversal(TreePruningException): """ Stop the traversal alltogether. The current node's ``depart_...`` method is not affected. The parent nodes ``depart_...`` methods are also called as usual. No other nodes are visited. This is an alternative to NodeFound that does not cause exception handling to trickle up to the caller. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = string.lower() if not isinstance(id, unicode): id = id.decode() id = id.translate(_non_id_translate_digraphs) id = id.translate(_non_id_translate) # get rid of non-ascii characters. # 'ascii' lowercase to prevent problems with turkish locale. id = unicodedata.normalize('NFKD', id).\ encode('ascii', 'ignore').decode('ascii') # shrink runs of whitespace and replace by hyphen id = _non_id_chars.sub('-', ' '.join(id.split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') _non_id_translate = { 0x00f8: u'o', # o with stroke 0x0111: u'd', # d with stroke 0x0127: u'h', # h with stroke 0x0131: u'i', # dotless i 0x0142: u'l', # l with stroke 0x0167: u't', # t with stroke 0x0180: u'b', # b with stroke 0x0183: u'b', # b with topbar 0x0188: u'c', # c with hook 0x018c: u'd', # d with topbar 0x0192: u'f', # f with hook 0x0199: u'k', # k with hook 0x019a: u'l', # l with bar 0x019e: u'n', # n with long right leg 0x01a5: u'p', # p with hook 0x01ab: u't', # t with palatal hook 0x01ad: u't', # t with hook 0x01b4: u'y', # y with hook 0x01b6: u'z', # z with stroke 0x01e5: u'g', # g with stroke 0x0225: u'z', # z with hook 0x0234: u'l', # l with curl 0x0235: u'n', # n with curl 0x0236: u't', # t with curl 0x0237: u'j', # dotless j 0x023c: u'c', # c with stroke 0x023f: u's', # s with swash tail 0x0240: u'z', # z with swash tail 0x0247: u'e', # e with stroke 0x0249: u'j', # j with stroke 0x024b: u'q', # q with hook tail 0x024d: u'r', # r with stroke 0x024f: u'y', # y with stroke } _non_id_translate_digraphs = { 0x00df: u'sz', # ligature sz 0x00e6: u'ae', # ae 0x0153: u'oe', # ligature oe 0x0238: u'db', # db digraph 0x0239: u'qp', # qp digraph } def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "clumsy/intellij-community", "path": "python/helpers/py2only/docutils/nodes.py", "copies": "5", "size": "64847", "license": "apache-2.0", "hash": 515670505707655000, "line_mean": 32.7744791667, "line_max": 79, "alpha_frac": 0.5914845714, "autogenerated": false, "ratio": 4.190706992374305, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7282191563774305, "avg_score": null, "num_lines": null }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import warnings import types import unicodedata # ============================== # Functional Node Base Classes # ============================== class Node(object): """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return True if sys.version_info < (3,): # on 2.x, str(node) will be a byte string with Unicode # characters > 255 escaped; on 3.x this is no longer necessary def __str__(self): return unicode(self).encode('raw_unicode_escape') def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return stop except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: if child.walk(visitor): stop = 1 break except SkipSiblings: pass except StopTraversal: stop = 1 return stop def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ call_depart = 1 stop = 0 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return stop except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: if child.walkabout(visitor): stop = 1 break except SkipSiblings: pass except SkipChildren: pass except StopTraversal: stop = 1 if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) return stop def _fast_traverse(self, cls): """Specialized traverse() that only supports instance checks.""" result = [] if isinstance(self, cls): result.append(self) for child in self.children: result.extend(child._fast_traverse(cls)) return result def _all_traverse(self): """Specialized traverse() that doesn't check for a condition.""" result = [] result.append(self) for child in self.children: result.extend(child._all_traverse()) return result def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ if ascend: siblings=1 # Check for special argument combinations that allow using an # optimized version of traverse() if include_self and descend and not siblings: if condition is None: return self._all_traverse() elif isinstance(condition, (types.ClassType, type)): return self._fast_traverse(condition) # Check if `condition` is a class (check for TypeType for Python # implementations that use only new-style classes, like PyPy). if isinstance(condition, (types.ClassType, type)): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) r = [] if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None if sys.version_info < (3,): class reprunicode(unicode): """ A class that removes the initial u from unicode's repr. """ def __repr__(self): return unicode.__repr__(self)[1:] else: reprunicode = unicode class Text(Node, reprunicode): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" if sys.version_info > (3,): def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" if isinstance(data, bytes): raise TypeError('expecting str data, not bytes') return reprunicode.__new__(cls, data) else: def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" return reprunicode.__new__(cls, data) def __init__(self, data, rawsource=''): self.rawsource = rawsource """The raw text from which this element was constructed.""" def shortrepr(self, maxlen=18): data = self if len(data) > maxlen: data = data[:maxlen-4] + ' ...' return '<%s: %s>' % (self.tagname, repr(reprunicode(data))) def __repr__(self): return self.shortrepr(maxlen=68) def _dom_node(self, domroot): return domroot.createTextNode(unicode(self)) def astext(self): return reprunicode(self) # Note about __unicode__: The implementation of __unicode__ here, # and the one raising NotImplemented in the superclass Node had # to be removed when changing Text to a subclass of unicode instead # of UserString, since there is no way to delegate the __unicode__ # call to the superclass unicode: # unicode itself does not have __unicode__ method to delegate to # and calling unicode(self) or unicode.__new__ directly creates # an infinite loop def copy(self): return self.__class__(reprunicode(self), rawsource=self.rawsource) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.splitlines(): result.append(indent + line + '\n') return ''.join(result) # rstrip and lstrip are used by substitution definitions where # they are expected to return a Text instance, this was formerly # taken care of by UserString. Note that then and now the # rawsource member is lost. def rstrip(self, chars=None): return self.__class__(reprunicode.rstrip(self, chars)) def lstrip(self, chars=None): return self.__class__(reprunicode.lstrip(self, chars)) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, list): value = ' '.join([serial_escape('%s' % (v,)) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([unicode(c) for c in self.children]), self.endtag()) else: return self.emptytag() if sys.version_info > (3,): # 2to3 doesn't convert __unicode__ to __str__ __str__ = __unicode__ def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, list): values = [serial_escape('%s' % (v,)) for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __contains__(self, key): # support both membership test for children and attributes # (has_key is translated to "in" by 2to3) if isinstance(key, basestring): return key in self.attributes return key in self.children def __getitem__(self, key): if isinstance(key, basestring): return self.attributes[key] elif isinstance(key, int): return self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, basestring): self.attributes[str(key)] = item elif isinstance(key, int): self.setup_child(item) self.children[key] = item elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, basestring): del self.attributes[key] elif isinstance(key, int): del self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return attr in self.attributes def delattr(self, attr): if attr in self.attributes: del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr # support operator in __contains__ = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(rawsource=self.rawsource, **self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def __getstate__(self): """ Return dict with unpicklable references removed. """ state = self.__dict__.copy() state['reporter'] = None state['transformer'] = None return state def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if id in self.ids and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and id not in self.ids: break else: id = '' while not id or id in self.ids: id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if name in self.nameids: self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if 'refuri' in node: refuri = node['refuri'] if old_node['names'] \ and 'refuri' in old_node \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return name in self.nameids # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if name in self.substitution_defs: msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class math_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, list) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class math(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block math math_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass class StopTraversal(TreePruningException): """ Stop the traversal alltogether. The current node's ``depart_...`` method is not affected. The parent nodes ``depart_...`` methods are also called as usual. No other nodes are visited. This is an alternative to NodeFound that does not cause exception handling to trickle up to the caller. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = string.lower() if not isinstance(id, unicode): id = id.decode() id = id.translate(_non_id_translate_digraphs) id = id.translate(_non_id_translate) # get rid of non-ascii characters. # 'ascii' lowercase to prevent problems with turkish locale. id = unicodedata.normalize('NFKD', id).\ encode('ascii', 'ignore').decode('ascii') # shrink runs of whitespace and replace by hyphen id = _non_id_chars.sub('-', ' '.join(id.split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') _non_id_translate = { 0x00f8: u'o', # o with stroke 0x0111: u'd', # d with stroke 0x0127: u'h', # h with stroke 0x0131: u'i', # dotless i 0x0142: u'l', # l with stroke 0x0167: u't', # t with stroke 0x0180: u'b', # b with stroke 0x0183: u'b', # b with topbar 0x0188: u'c', # c with hook 0x018c: u'd', # d with topbar 0x0192: u'f', # f with hook 0x0199: u'k', # k with hook 0x019a: u'l', # l with bar 0x019e: u'n', # n with long right leg 0x01a5: u'p', # p with hook 0x01ab: u't', # t with palatal hook 0x01ad: u't', # t with hook 0x01b4: u'y', # y with hook 0x01b6: u'z', # z with stroke 0x01e5: u'g', # g with stroke 0x0225: u'z', # z with hook 0x0234: u'l', # l with curl 0x0235: u'n', # n with curl 0x0236: u't', # t with curl 0x0237: u'j', # dotless j 0x023c: u'c', # c with stroke 0x023f: u's', # s with swash tail 0x0240: u'z', # z with swash tail 0x0247: u'e', # e with stroke 0x0249: u'j', # j with stroke 0x024b: u'q', # q with hook tail 0x024d: u'r', # r with stroke 0x024f: u'y', # y with stroke } _non_id_translate_digraphs = { 0x00df: u'sz', # ligature sz 0x00e6: u'ae', # ae 0x0153: u'oe', # ligature oe 0x0238: u'db', # db digraph 0x0239: u'qp', # qp digraph } def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "ajaxsys/dict-admin", "path": "docutils/nodes.py", "copies": "2", "size": "66890", "license": "bsd-3-clause", "hash": 1256835174158147800, "line_mean": 32.7847113885, "line_max": 79, "alpha_frac": 0.5747645388, "autogenerated": false, "ratio": 4.271664857270579, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5846429396070579, "avg_score": null, "num_lines": null }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import warnings import types import unicodedata # ============================== # Functional Node Base Classes # ============================== class Node(object): """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return True if sys.version_info < (3,): # on 2.x, str(node) will be a byte string with Unicode # characters > 255 escaped; on 3.x this is no longer necessary def __str__(self): return unicode(self).encode('raw_unicode_escape') def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ stop = False visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return stop except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: if child.walk(visitor): stop = True break except SkipSiblings: pass except StopTraversal: stop = True return stop def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ call_depart = True stop = False visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return stop except SkipDeparture: call_depart = False children = self.children try: for child in children[:]: if child.walkabout(visitor): stop = True break except SkipSiblings: pass except SkipChildren: pass except StopTraversal: stop = True if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) return stop def _fast_traverse(self, cls): """Specialized traverse() that only supports instance checks.""" result = [] if isinstance(self, cls): result.append(self) for child in self.children: result.extend(child._fast_traverse(cls)) return result def _all_traverse(self): """Specialized traverse() that doesn't check for a condition.""" result = [] result.append(self) for child in self.children: result.extend(child._all_traverse()) return result def traverse(self, condition=None, include_self=True, descend=True, siblings=False, ascend=False): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=True)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ if ascend: siblings=True # Check for special argument combinations that allow using an # optimized version of traverse() if include_self and descend and not siblings: if condition is None: return self._all_traverse() elif isinstance(condition, (types.ClassType, type)): return self._fast_traverse(condition) # Check if `condition` is a class (check for TypeType for Python # implementations that use only new-style classes, like PyPy). if isinstance(condition, (types.ClassType, type)): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) r = [] if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse(include_self=True, descend=True, siblings=False, ascend=False, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=True, descend=descend, siblings=False, ascend=False, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=False, descend=True, siblings=False, ascend=False): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None if sys.version_info < (3,): class reprunicode(unicode): """ A class that removes the initial u from unicode's repr. """ def __repr__(self): return unicode.__repr__(self)[1:] else: reprunicode = unicode class Text(Node, reprunicode): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" if sys.version_info > (3,): def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" if isinstance(data, bytes): raise TypeError('expecting str data, not bytes') return reprunicode.__new__(cls, data) else: def __new__(cls, data, rawsource=None): """Prevent the rawsource argument from propagating to str.""" return reprunicode.__new__(cls, data) def __init__(self, data, rawsource=''): self.rawsource = rawsource """The raw text from which this element was constructed.""" def shortrepr(self, maxlen=18): data = self if len(data) > maxlen: data = data[:maxlen-4] + ' ...' return '<%s: %s>' % (self.tagname, repr(reprunicode(data))) def __repr__(self): return self.shortrepr(maxlen=68) def _dom_node(self, domroot): return domroot.createTextNode(unicode(self)) def astext(self): return reprunicode(self) # Note about __unicode__: The implementation of __unicode__ here, # and the one raising NotImplemented in the superclass Node had # to be removed when changing Text to a subclass of unicode instead # of UserString, since there is no way to delegate the __unicode__ # call to the superclass unicode: # unicode itself does not have __unicode__ method to delegate to # and calling unicode(self) or unicode.__new__ directly creates # an infinite loop def copy(self): return self.__class__(reprunicode(self), rawsource=self.rawsource) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.splitlines(): result.append(indent + line + '\n') return ''.join(result) # rstrip and lstrip are used by substitution definitions where # they are expected to return a Text instance, this was formerly # taken care of by UserString. Note that then and now the # rawsource member is lost. def rstrip(self, chars=None): return self.__class__(reprunicode.rstrip(self, chars)) def lstrip(self, chars=None): return self.__class__(reprunicode.lstrip(self, chars)) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, list): value = ' '.join([serial_escape('%s' % (v,)) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([unicode(c) for c in self.children]), self.endtag()) else: return self.emptytag() if sys.version_info > (3,): # 2to3 doesn't convert __unicode__ to __str__ __str__ = __unicode__ def starttag(self, quoteattr=None): # the optional arg is used by the docutils_xml writer if quoteattr is None: quoteattr = pseudo_quoteattr parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) continue if isinstance(value, list): values = [serial_escape('%s' % (v,)) for v in value] value = ' '.join(values) else: value = unicode(value) value = quoteattr(value) parts.append(u'%s=%s' % (name, value)) return u'<%s>' % u' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % u' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __contains__(self, key): # support both membership test for children and attributes # (has_key is translated to "in" by 2to3) if isinstance(key, basestring): return key in self.attributes return key in self.children def __getitem__(self, key): if isinstance(key, basestring): return self.attributes[key] elif isinstance(key, int): return self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, basestring): self.attributes[str(key)] = item elif isinstance(key, int): self.setup_child(item) self.children[key] = item elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, basestring): del self.attributes[key] elif isinstance(key, int): del self.children[key] elif isinstance(key, types.SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return attr in self.attributes def delattr(self, attr): if attr in self.attributes: del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr # support operator in __contains__ = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(rawsource=self.rawsource, **self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def __getstate__(self): """ Return dict with unpicklable references removed. """ state = self.__dict__.copy() state['reporter'] = None state['transformer'] = None return state def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if id in self.ids and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and id not in self.ids: break else: id = '' while not id or id in self.ids: id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if name in self.nameids: self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if 'refuri' in node: refuri = node['refuri'] if old_node['names'] \ and 'refuri' in old_node \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return name in self.nameids # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=True) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if name in self.substitution_defs: msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class math_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, list) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class math(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block math math_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass class StopTraversal(TreePruningException): """ Stop the traversal alltogether. The current node's ``depart_...`` method is not affected. The parent nodes ``depart_...`` methods are also called as usual. No other nodes are visited. This is an alternative to NodeFound that does not cause exception handling to trickle up to the caller. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = string.lower() if not isinstance(id, unicode): id = id.decode() id = id.translate(_non_id_translate_digraphs) id = id.translate(_non_id_translate) # get rid of non-ascii characters. # 'ascii' lowercase to prevent problems with turkish locale. id = unicodedata.normalize('NFKD', id).\ encode('ascii', 'ignore').decode('ascii') # shrink runs of whitespace and replace by hyphen id = _non_id_chars.sub('-', ' '.join(id.split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') _non_id_translate = { 0x00f8: u'o', # o with stroke 0x0111: u'd', # d with stroke 0x0127: u'h', # h with stroke 0x0131: u'i', # dotless i 0x0142: u'l', # l with stroke 0x0167: u't', # t with stroke 0x0180: u'b', # b with stroke 0x0183: u'b', # b with topbar 0x0188: u'c', # c with hook 0x018c: u'd', # d with topbar 0x0192: u'f', # f with hook 0x0199: u'k', # k with hook 0x019a: u'l', # l with bar 0x019e: u'n', # n with long right leg 0x01a5: u'p', # p with hook 0x01ab: u't', # t with palatal hook 0x01ad: u't', # t with hook 0x01b4: u'y', # y with hook 0x01b6: u'z', # z with stroke 0x01e5: u'g', # g with stroke 0x0225: u'z', # z with hook 0x0234: u'l', # l with curl 0x0235: u'n', # n with curl 0x0236: u't', # t with curl 0x0237: u'j', # dotless j 0x023c: u'c', # c with stroke 0x023f: u's', # s with swash tail 0x0240: u'z', # z with swash tail 0x0247: u'e', # e with stroke 0x0249: u'j', # j with stroke 0x024b: u'q', # q with hook tail 0x024d: u'r', # r with stroke 0x024f: u'y', # y with stroke } _non_id_translate_digraphs = { 0x00df: u'sz', # ligature sz 0x00e6: u'ae', # ae 0x0153: u'oe', # ligature oe 0x0238: u'db', # db digraph 0x0239: u'qp', # qp digraph } def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') def pseudo_quoteattr(value): """Quote attributes for pseudo-xml""" return '"%s"' % value # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "ddd332/presto", "path": "presto-docs/target/sphinx/docutils/nodes.py", "copies": "4", "size": "65462", "license": "apache-2.0", "hash": 4041163557065037000, "line_mean": 32.847983454, "line_max": 79, "alpha_frac": 0.5916103999, "autogenerated": false, "ratio": 4.201668806161746, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6793279206061746, "avg_score": null, "num_lines": null }
# $Id: ntp.py 382 2006-07-31 04:07:52Z jonojono $ """Network Time Protocol.""" import time import dpkt # NTP v4 # Leap Indicator (LI) Codes NO_WARNING = 0 LAST_MINUTE_61_SECONDS = 1 LAST_MINUTE_59_SECONDS = 2 ALARM_CONDITION = 3 # Mode Codes RESERVED = 0 SYMMETRIC_ACTIVE = 1 SYMMETRIC_PASSIVE = 2 CLIENT = 3 SERVER = 4 BROADCAST = 5 CONTROL_MESSAGE = 6 PRIVATE = 7 class NTP(dpkt.Packet): __hdr__ = ( ('flags', 'B', 0), ('stratum', 'B', 0), ('interval', 'B', 0), ('precision', 'B', 0), ('delay', 'I', 0), ('dispersion', 'I', 0), ('id', '4s', 0), ('update_time', '8s', 0), ('originate_time', '8s', 0), ('receive_time', '8s', 0), ('transmit_time', '8s', 0) ) def _get_v(self): return (self.flags >> 3) & 0x7 def _set_v(self, v): self.flags = (self.flags & ~0x38) | ((v & 0x7) << 3) v = property(_get_v, _set_v) def _get_li(self): return (self.flags >> 6) & 0x3 def _set_li(self, li): self.flags = (self.flags & ~0xc0) | ((li & 0x3) << 6) li = property(_get_li, _set_li) def _get_mode(self): return (self.flags & 0x7) def _set_mode(self, mode): self.flags = (self.flags & ~0x7) | (mode & 0x7) mode = property(_get_mode, _set_mode) if __name__ == '__main__': import unittest class NTPTestCase(unittest.TestCase): def testPack(self): n = NTP(self.s) self.failUnless(self.s == str(n)) def testUnpack(self): n = NTP(self.s) self.failUnless(n.li == NO_WARNING) self.failUnless(n.v == 4) self.failUnless(n.mode == SERVER) self.failUnless(n.stratum == 2) self.failUnless(n.id == '\xc1\x02\x04\x02') # test get/set functions n.li = ALARM_CONDITION n.v = 3 n.mode = CLIENT self.failUnless(n.li == ALARM_CONDITION) self.failUnless(n.v == 3) self.failUnless(n.mode == CLIENT) s = '\x24\x02\x04\xef\x00\x00\x00\x84\x00\x00\x33\x27\xc1\x02\x04\x02\xc8\x90\xec\x11\x22\xae\x07\xe5\xc8\x90\xf9\xd9\xc0\x7e\x8c\xcd\xc8\x90\xf9\xd9\xda\xc5\xb0\x78\xc8\x90\xf9\xd9\xda\xc6\x8a\x93' unittest.main()
{ "repo_name": "MercenaryLogic/StompingGround", "path": "stompingground/dpkt/ntp.py", "copies": "1", "size": "2307", "license": "mit", "hash": 64271993063687180, "line_mean": 26.4642857143, "line_max": 206, "alpha_frac": 0.5253576073, "autogenerated": false, "ratio": 2.639588100686499, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8600595383647988, "avg_score": 0.012870064867702282, "num_lines": 84 }
# $Id: ntp.py 48 2008-05-27 17:31:15Z yardley $ """Network Time Protocol.""" import dpkt # NTP v4 # Leap Indicator (LI) Codes NO_WARNING = 0 LAST_MINUTE_61_SECONDS = 1 LAST_MINUTE_59_SECONDS = 2 ALARM_CONDITION = 3 # Mode Codes RESERVED = 0 SYMMETRIC_ACTIVE = 1 SYMMETRIC_PASSIVE = 2 CLIENT = 3 SERVER = 4 BROADCAST = 5 CONTROL_MESSAGE = 6 PRIVATE = 7 class NTP(dpkt.Packet): __hdr__ = ( ('flags', 'B', 0), ('stratum', 'B', 0), ('interval', 'B', 0), ('precision', 'B', 0), ('delay', 'I', 0), ('dispersion', 'I', 0), ('id', '4s', 0), ('update_time', '8s', 0), ('originate_time', '8s', 0), ('receive_time', '8s', 0), ('transmit_time', '8s', 0) ) def _get_v(self): return (self.flags >> 3) & 0x7 def _set_v(self, v): self.flags = (self.flags & ~0x38) | ((v & 0x7) << 3) v = property(_get_v, _set_v) def _get_li(self): return (self.flags >> 6) & 0x3 def _set_li(self, li): self.flags = (self.flags & ~0xc0) | ((li & 0x3) << 6) li = property(_get_li, _set_li) def _get_mode(self): return (self.flags & 0x7) def _set_mode(self, mode): self.flags = (self.flags & ~0x7) | (mode & 0x7) mode = property(_get_mode, _set_mode) if __name__ == '__main__': import unittest class NTPTestCase(unittest.TestCase): def testPack(self): n = NTP(self.s) self.failUnless(self.s == str(n)) def testUnpack(self): n = NTP(self.s) self.failUnless(n.li == NO_WARNING) self.failUnless(n.v == 4) self.failUnless(n.mode == SERVER) self.failUnless(n.stratum == 2) self.failUnless(n.id == '\xc1\x02\x04\x02') # test get/set functions n.li = ALARM_CONDITION n.v = 3 n.mode = CLIENT self.failUnless(n.li == ALARM_CONDITION) self.failUnless(n.v == 3) self.failUnless(n.mode == CLIENT) s = '\x24\x02\x04\xef\x00\x00\x00\x84\x00\x00\x33\x27\xc1\x02\x04\x02\xc8\x90\xec\x11\x22\xae\x07\xe5\xc8\x90\xf9\xd9\xc0\x7e\x8c\xcd\xc8\x90\xf9\xd9\xda\xc5\xb0\x78\xc8\x90\xf9\xd9\xda\xc6\x8a\x93' unittest.main()
{ "repo_name": "ashrith/dpkt", "path": "dpkt/ntp.py", "copies": "15", "size": "2293", "license": "bsd-3-clause", "hash": -5913369074134112000, "line_mean": 26.6265060241, "line_max": 206, "alpha_frac": 0.5233318796, "autogenerated": false, "ratio": 2.6386651323360186, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
#$Id: NTSerializer.py,v 1.6 2003/10/29 15:25:24 kendall Exp $ from rdflib.syntax.serializers import Serializer class NTSerializer(Serializer): def __init__(self, store): """ I serialize RDF graphs in NTriples format. """ super(NTSerializer, self).__init__(store) def serialize(self, stream, base=None, encoding=None, **args): if base is not None: print "TODO: NTSerializer does not support base" encoding = self.encoding write = lambda triple: stream.write((triple[0].n3() + u" " + \ triple[1].n3() + u" " + _xmlcharref_encode(triple[2].n3()) + u" .\n").encode(encoding, "replace")) map(write, self.store) stream.write("\n") # from http://code.activestate.com/recipes/303668/ def _xmlcharref_encode(unicode_data, encoding="ascii"): """Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler.""" chars = [] # nothing to do about xmlchars, but replace newlines with escapes: unicode_data=unicode_data.replace("\n","\\n") if unicode_data.startswith('"""'): unicode_data=unicode_data[2:-2] # Step through the unicode_data string one character at a time in # order to catch unencodable characters: for char in unicode_data: try: chars.append(char.encode(encoding, 'strict')) except UnicodeError: chars.append('\u%04X' % ord(char)) return ''.join(chars)
{ "repo_name": "alcides/rdflib", "path": "rdflib/syntax/serializers/NTSerializer.py", "copies": "1", "size": "1480", "license": "bsd-3-clause", "hash": 2601552337186026500, "line_mean": 35.0975609756, "line_max": 143, "alpha_frac": 0.6135135135, "autogenerated": false, "ratio": 3.7373737373737375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9708868910171249, "avg_score": 0.028403668140497853, "num_lines": 41 }
# $Id: numfmt.py,v 1.4 2013/10/21 06:59:21 olpa Exp $ import re re_maybe_numfmt = re.compile('[0#.,]*[0#][0#.,]*') def extract_number_format(s_fmt): # If don't know what does the format "Standard/GENERAL" mean. # As far as I understand, the presentation can differ depending # on the locale and user settings. Here is a my proposal. if 'GENERAL' == s_fmt: return (None, '#', '#') # Find the number-part m = re_maybe_numfmt.search(s_fmt) if m is None: return None # return s_numfmt = str(m.group(0)) # Only one comma pos_comma = s_numfmt.find(',') if pos_comma > -1: pos2 = s_numfmt.find(',', pos_comma+1) if pos2 > -1: return None # return # Only one dot pos_dot = s_numfmt.find('.') if pos_dot > -1: pos2 = s_numfmt.find('.', pos_dot+1) if pos2 > -1: return None # return # Exactly three positions between comma and dot if pos_comma > -1: pos2 = pos_dot if pos_dot > -1 else len(s_numfmt) if pos2 - pos_comma != 4: return None # return # Create parts (part_above1000, part_below1000, part_below1) = (None, None, None) if pos_dot > -1: part_below1 = s_numfmt[pos_dot+1:] s_numfmt = s_numfmt[:pos_dot] if pos_comma > -1: part_above1000 = s_numfmt[:pos_comma] part_below1000 = s_numfmt[pos_comma+1:] else: part_below1000 = s_numfmt return (part_above1000, part_below1000, part_below1) def format_number(f, a_fmt, div1000, div1): (part_above1000, part_below1000, part_below1) = a_fmt s_fmt = '%' if f < 0: is_negative = 1 f = abs(f) else: is_negative = 0 # Float to string with a minimal precision after comma. # Filling the integer part with '0' at left doesn't work for %f. precision = len(part_below1) if part_below1 else 0 s_fmt = '%.' + str(precision) + 'f' s_f = s_fmt % f # Postprocessing. Drop insignificant zeros. while precision: if '0' == part_below1[precision-1]: break if '0' != s_f[-1]: break s_f = s_f[:-1] precision = precision - 1 if '.' == s_f[-1]: s_f = s_f[:-1] precision = 0 # Add significant zeros part_above1 = part_above1000+part_below1000 if part_above1000 else part_below1000 i = part_above1.find('0') if i > -1: if precision: need_len = len(part_above1) - i + 1 + precision else: need_len = len(part_above1) - i if need_len > len(s_f): s_f = s_f.rjust(need_len, '0') # Put dots and commas if '.' != div1: s_f = s_f.replace('.', div1) if part_above1000: if precision: div_pos = len(s_f) - precision - 4 else: div_pos = len(s_f) - 3 while div_pos > 0: s_f = s_f[:div_pos] + div1000 + s_f[div_pos:] div_pos -= 3 # Add negative sign if is_negative: if '0' == s_f[0]: s_f = '-' + s_f[1:] else: s_f = '-' + s_f return s_f
{ "repo_name": "youlanhai/ExcelToCode", "path": "xl2code/numfmt.py", "copies": "1", "size": "3005", "license": "mit", "hash": 6504459173429956000, "line_mean": 30.3020833333, "line_max": 83, "alpha_frac": 0.5550748752, "autogenerated": false, "ratio": 2.946078431372549, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4001153306572549, "avg_score": null, "num_lines": null }
""" This file has common functions for interacting with Splunk for use in the Octopus TA integrations. """ import ConfigParser import os, logging, sys, time import splunk.bundle as sb import splunk.Intersplunk as isp from splunk.clilib import cli_common as cli import splunk def setup_logging(): """ Setup logging Log is written to /opt/splunk/var/log/splunk/octopus.log """ logger = logging.getLogger('splunk.octopus') SPLUNK_HOME = os.environ['SPLUNK_HOME'] LOGGING_DEFAULT_CONFIG_FILE = os.path.join(SPLUNK_HOME, 'etc', 'log.cfg') LOGGING_LOCAL_CONFIG_FILE = os.path.join(SPLUNK_HOME, 'etc', 'log-local.cfg') LOGGING_STANZA_NAME = 'python' LOGGING_FILE_NAME = "octopus.log" BASE_LOG_PATH = os.path.join('var', 'log', 'splunk') LOGGING_FORMAT = "%(asctime)s %(levelname)-s\t%(module)s:%(lineno)d - %(message)s" splunk_log_handler = logging.handlers.RotatingFileHandler(os.path.join(SPLUNK_HOME, BASE_LOG_PATH, LOGGING_FILE_NAME), mode='a') splunk_log_handler.setFormatter(logging.Formatter(LOGGING_FORMAT)) logger.addHandler(splunk_log_handler) splunk.setupSplunkLogger(logger, LOGGING_DEFAULT_CONFIG_FILE, LOGGING_LOCAL_CONFIG_FILE, LOGGING_STANZA_NAME) return logger def getSelfConfStanza(stanza): appdir = os.path.dirname(os.path.dirname(__file__)) apikeyconfpath = os.path.join(appdir, "default", "octopus.conf") apikeyconf = cli.readConfFile(apikeyconfpath) localconfpath = os.path.join(appdir, "local", "octopus.conf") if os.path.exists(localconfpath): localconf = cli.readConfFile(localconfpath) for name, content in localconf.items(): if name in apikeyconf: apikeyconf[name].update(content) else: apikeyconf[name] = content return apikeyconf[stanza] def writeCheckPoint(sourcetype, checkpoint): logger = setup_logging() logger.info(time.time()) appdir = os.path.dirname(os.path.dirname(__file__)) last_eventid_filepath = os.path.join(appdir, "local", "octopus-" + sourcetype + ".chk") try: last_eventid_file = open(last_eventid_filepath,'w') last_eventid_file.write(checkpoint) last_eventid_file.close() except IOError: logger.error('Error: Failed to write last_eventid to file: ' + last_eventid_filepath + '\n') sys.exit(2) def readCheckPoint(sourcetype): logger = setup_logging() logger.info(time.time()) appdir = os.path.dirname(os.path.dirname(__file__)) last_eventid_filepath = os.path.join(appdir, "local", "octopus-" + sourcetype + ".chk") checkpoint = 0; if os.path.isfile(last_eventid_filepath): try: last_eventid_file = open(last_eventid_filepath,'r') checkpoint = int(last_eventid_file.readline()) last_eventid_file.close() except IOError: logger.error('Error: Failed to read last_eventid file, ' + last_eventid_filepath + '\n') sys.exit(2) else: logger.warning('Warning: ' + last_eventid_filepath + ' file not found! Starting from zero. \n') return checkpoint
{ "repo_name": "cmeerbeek/splunk-addon-octopus-deploy", "path": "TA-OctopusNT-Fwd/bin/octopus_common.py", "copies": "2", "size": "3107", "license": "mit", "hash": -7830624025907502000, "line_mean": 34.3181818182, "line_max": 131, "alpha_frac": 0.7019633087, "autogenerated": false, "ratio": 3.0977068793619145, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4799670188061914, "avg_score": null, "num_lines": null }
import splunk.admin as admin import splunk.entity as en # import your required python modules ''' Copyright (C) 2005 - 2010 Splunk Inc. All Rights Reserved. Description: This skeleton python script handles the parameters in the configuration page. handleList method: lists configurable parameters in the configuration page corresponds to handleractions = list in restmap.conf handleEdit method: controls the parameters and saves the values corresponds to handleractions = edit in restmap.conf ''' class ConfigApp(admin.MConfigHandler): ''' Set up supported arguments ''' def setup(self): if self.requestedAction == admin.ACTION_EDIT: for arg in ['hostname', 'protocol', 'apikey']: self.supportedArgs.addOptArg(arg) ''' Read the initial values of the parameters from the custom file myappsetup.conf, and write them to the setup page. If the app has never been set up, uses .../app_name/default/myappsetup.conf. If app has been set up, looks at .../local/myappsetup.conf first, then looks at .../default/myappsetup.conf only if there is no value for a field in .../local/myappsetup.conf For boolean fields, may need to switch the true/false setting. For text fields, if the conf file says None, set to the empty string. ''' def handleList(self, confInfo): confDict = self.readConf("octopus") if None != confDict: for stanza, settings in confDict.items(): for key, val in settings.items(): if key in ['hostname'] and val in [None, '']: val = '' elif key in ['protocol'] and val in [None, '']: val = '' elif key in ['apikey'] and val in [None, '']: val = '' confInfo[stanza].append(key, val) ''' After user clicks Save on setup page, take updated parameters, normalize them, and save them somewhere ''' def handleEdit(self, confInfo): name = self.callerArgs.id args = self.callerArgs if self.callerArgs.data['hostname'][0] in [None, '']: self.callerArgs.data['hostname'][0] = '' if self.callerArgs.data['protocol'][0] in [None, '']: self.callerArgs.data['protocol'][0] = '' if self.callerArgs.data['apikey'][0] in [None, '']: self.callerArgs.data['apikey'][0] = '' ''' Since we are using a conf file to store parameters, write them to the [octopus] stanza in app_name/local/octopus.conf ''' self.writeConf('octopus', 'octopus', self.callerArgs.data) # initialize the handler admin.init(ConfigApp, admin.CONTEXT_NONE)
{ "repo_name": "cmeerbeek/splunk-addon-octopus-deploy", "path": "TA-OctopusNIX-Fwd/bin/octopus_conf_handler.py", "copies": "2", "size": "2769", "license": "mit", "hash": -1487339614324145400, "line_mean": 31.2093023256, "line_max": 91, "alpha_frac": 0.6504153124, "autogenerated": false, "ratio": 3.7879616963064295, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021852607600331156, "num_lines": 86 }
"""$Id: opml.py 699 2006-09-25 02:01:18Z rubys $""" __author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>" __version__ = "$Revision: 699 $" __date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $" __copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim" from base import validatorBase from validators import * from logging import * import re # # Outline Processor Markup Language element. # class opml(validatorBase): versionList = ['1.0', '1.1'] def validate(self): self.setFeedType(TYPE_OPML) if (None,'version') in self.attrs.getNames(): if self.attrs[(None,'version')] not in opml.versionList: self.log(InvalidOPMLVersion({"parent":self.parent.name, "element":self.name, "value":self.attrs[(None,'version')]})) elif self.name != 'outlineDocument': self.log(MissingAttribute({"parent":self.parent.name, "element":self.name, "attr":"version"})) if 'head' not in self.children: self.log(MissingElement({"parent":self.name, "element":"head"})) if 'body' not in self.children: self.log(MissingElement({"parent":self.name, "element":"body"})) def getExpectedAttrNames(self): return [(None, u'version')] def do_head(self): return opmlHead() def do_body(self): return opmlBody() class opmlHead(validatorBase): def do_title(self): return safeHtml(), noduplicates() def do_dateCreated(self): return rfc822(), noduplicates() def do_dateModified(self): return rfc822(), noduplicates() def do_ownerName(self): return safeHtml(), noduplicates() def do_ownerEmail(self): return email(), noduplicates() def do_expansionState(self): return commaSeparatedLines(), noduplicates() def do_vertScrollState(self): return positiveInteger(), nonblank(), noduplicates() def do_windowTop(self): return positiveInteger(), nonblank(), noduplicates() def do_windowLeft(self): return positiveInteger(), nonblank(), noduplicates() def do_windowBottom(self): return positiveInteger(), nonblank(), noduplicates() def do_windowRight(self): return positiveInteger(), nonblank(), noduplicates() class commaSeparatedLines(text): linenumbers_re=re.compile('^(\d+(,\s*\d+)*)?$') def validate(self): if not self.linenumbers_re.match(self.value): self.log(InvalidExpansionState({"parent":self.parent.name, "element":self.name, "value":self.value})) class opmlBody(validatorBase): def validate(self): if 'outline' not in self.children: self.log(MissingElement({"parent":self.name, "element":"outline"})) def do_outline(self): return opmlOutline() class opmlOutline(validatorBase,rfc822,safeHtml,iso639,rfc2396_full,truefalse): versionList = ['RSS', 'RSS1', 'RSS2', 'scriptingNews'] def getExpectedAttrNames(self): return [ (None, u'category'), (None, u'created'), (None, u'description'), (None, u'htmlUrl'), (None, u'isBreakpoint'), (None, u'isComment'), (None, u'language'), (None, u'text'), (None, u'title'), (None, u'type'), (None, u'url'), (None, u'version'), (None, u'xmlUrl'), ] def validate(self): if not (None,'text') in self.attrs.getNames(): self.log(MissingAttribute({"parent":self.parent.name, "element":self.name, "attr":"text"})) if (None,'type') in self.attrs.getNames(): if self.attrs[(None,'type')].lower() == 'rss': if not (None,'xmlUrl') in self.attrs.getNames(): self.log(MissingXmlURL({"parent":self.parent.name, "element":self.name})) if not (None,'title') in self.attrs.getNames(): self.log(MissingTitleAttr({"parent":self.parent.name, "element":self.name})) elif self.attrs[(None,'type')].lower() == 'link': if not (None,'url') in self.attrs.getNames(): self.log(MissingUrlAttr({"parent":self.parent.name, "element":self.name})) else: self.log(InvalidOutlineType({"parent":self.parent.name, "element":self.name, "value":self.attrs[(None,'type')]})) if (None,'version') in self.attrs.getNames(): if self.attrs[(None,'version')] not in opmlOutline.versionList: self.log(InvalidOutlineVersion({"parent":self.parent.name, "element":self.name, "value":self.attrs[(None,'version')]})) if len(self.attrs)>1 and not (None,u'type') in self.attrs.getNames(): for name in u'description htmlUrl language title version xmlUrl'.split(): if (None, name) in self.attrs.getNames(): self.log(MissingOutlineType({"parent":self.parent.name, "element":self.name})) break if (None,u'created') in self.attrs.getNames(): self.name = 'created' self.value = self.attrs[(None,'created')] rfc822.validate(self) if (None,u'description') in self.attrs.getNames(): self.name = 'description' self.value = self.attrs[(None,'description')] safeHtml.validate(self) if (None,u'htmlUrl') in self.attrs.getNames(): self.name = 'htmlUrl' self.value = self.attrs[(None,'htmlUrl')] rfc2396_full.validate(self) if (None,u'isBreakpoint') in self.attrs.getNames(): self.name = 'isBreakpoint' self.value = self.attrs[(None,'isBreakpoint')] truefalse.validate(self) if (None,u'isComment') in self.attrs.getNames(): self.name = 'isComment' self.value = self.attrs[(None,'isComment')] truefalse.validate(self) if (None,u'language') in self.attrs.getNames(): self.name = 'language' self.value = self.attrs[(None,'language')] iso639.validate(self) if (None,u'title') in self.attrs.getNames(): self.name = 'title' self.value = self.attrs[(None,'title')] safeHtml.validate(self) if (None,u'text') in self.attrs.getNames(): self.name = 'text' self.value = self.attrs[(None,'text')] safeHtml.validate(self) if (None,u'url') in self.attrs.getNames(): self.name = 'url' self.value = self.attrs[(None,'url')] rfc2396_full.validate(self) def characters(self, string): if not self.value: if string.strip(): self.log(UnexpectedText({"element":self.name,"parent":self.parent.name})) self.value = string def do_outline(self): return opmlOutline()
{ "repo_name": "waltharius/NewsBlur", "path": "vendor/feedvalidator/opml.py", "copies": "16", "size": "6331", "license": "mit", "hash": 9109807740678620000, "line_mean": 31.3010204082, "line_max": 127, "alpha_frac": 0.6422366135, "autogenerated": false, "ratio": 3.4019344438473937, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
# $Id: PARHelpers.py 344 2012-12-13 13:10:53Z krasznaa $ ########################################################################## # Project: SFrame - ROOT-based analysis framework for ATLAS # # # # author Stefan Ask <Stefan.Ask@cern.ch> - Manchester # # author David Berge <David.Berge@cern.ch> - CERN # # author Johannes Haller <Johannes.Haller@cern.ch> - Hamburg # # author A. Krasznahorkay <Attila.Krasznahorkay@cern.ch> - NYU/Debrecen # # # ########################################################################## ## @package PARHelpers # @short Functions for creating a PAR file from an SFrame package # # This package collects the functions used by sframe_parMaker.py # to create PAR packages out of SFrame packages during compilation. # It is possible to use the functions directly, by just doing: # # <code> # >>> import PARHelpers # </code> # Import the needed module(s): import os.path import os import re import shutil ## PAR package creator function # # This function creates PAR packages based on a number of parameters. # # @param srcdir Base directory from which the PAR package is made # @param makefile Name of the makefile in the package # @param include Name of the include directory in the package # @param src Name of the source file directory in the package # @param proofdir Name of the directory holding the special PROOF files # @param output Name of the output file # @param verbose <code>True</code> if verbose printout is requested def PARMaker( srcdir, makefile, include, src, proofdir, output, verbose ): # Tell the user what we're doing: if verbose: print " >>" print " >> Running PARHelpers.PARMaker" print " >>" pass # Split the output file name into constituents: ( outputdir, outputfile ) = os.path.split( output ) ( outputbase, outputext ) = os.path.splitext( outputfile ) if verbose: print " >> outputdir = " + outputdir print " >> outputbase = " + outputbase print " >> outputext = " + outputext pass # Check that the output file name has the correct extension: if( outputext != ".par" ): print "ERROR: The output file's extension must be \".par\"" return # Create an appropriate temporary directory for the package creation: import tempfile tempdir = tempfile.mkdtemp() if verbose: print " >> tempdir = " + tempdir pass # Create the temporary directories for the package: os.system( "rm -rf " + tempdir + "/" + outputbase ) os.mkdir( tempdir + "/" + outputbase ) os.mkdir( tempdir + "/" + outputbase + "/" + include ) os.mkdir( tempdir + "/" + outputbase + "/" + src ) os.mkdir( tempdir + "/" + outputbase + "/PROOF-INF" ) # Get the list of header files to be included in the package: headers = os.listdir( srcdir + include ) headers_filt = [ file for file in headers if ( re.search( "\.h$", file ) or re.search( "\.icc$", file ) ) ] if verbose: print " >> headers = " + ", ".join( headers_filt ) pass # Get the list of source files to be included in the package: sources = os.listdir( srcdir + src ) sources_filt = [ file for file in sources if ( ( re.search( "\.cxx$", file ) or re.search( "\.h$", file ) ) and not ( re.search( "\_Dict\.cxx$", file ) or re.search( "\_Dict\.h$", file ) ) ) ] if verbose: print " >> sources = " + ", ".join( sources_filt ) pass # Copy the header and source files to the correct directories, and # then transform them in-situ: for header in headers_filt: shutil.copy( srcdir + "/" + include + "/" + header, tempdir + "/" + outputbase + "/" + include ) SourceTransform( tempdir + "/" + outputbase + "/" + include + "/" + header ) pass for source in sources_filt: shutil.copy( srcdir + "/" + src + "/" + source, tempdir + "/" + outputbase + "/" + src ) SourceTransform( tempdir + "/" + outputbase + "/" + src + "/" + source ) pass # Copy the package makefile to the correct directory: shutil.copy( srcdir + "/" + makefile, tempdir + "/" + outputbase ) ( makefiledir, makefilename ) = os.path.split( makefile ) MakefileTransform( tempdir + "/" + outputbase + "/" + makefilename, verbose ) # Create the Makefile.proof makefile fragment: MakefileProof( tempdir + "/" + outputbase + "/Makefile.proof", verbose ) # Get the list of files in the proof directory: proof = os.listdir( srcdir + proofdir ) proof_filt = [ file for file in proof if ( not re.search( "~$", file ) and os.path.isfile( srcdir + "/" + proofdir + "/" + file ) ) ] if verbose: print " >> proof files = " + ", ".join( proof_filt ) pass # Copy the proof files: for pfile in proof_filt: shutil.copy( srcdir + "/" + proofdir + "/" + pfile, tempdir + "/" + outputbase + "/PROOF-INF" ) pass # Create the PAR package: if verbose: print " >> Now creating " + output pass os.system( "tar -C " + tempdir + " -czf " + output + " " + outputbase + "/" ) # Remove the temporary directory: if verbose: print " >> Now removing " + tempdir + "/" + outputbase pass os.system( "rm -rf " + tempdir + "/" + outputbase ) # The temporary directory itself has to be removed as well: os.system( "rmdir " + tempdir ) # Tell the user what we did: print " Created PAR package: " + output return ## Transform the contents of the specified makefile for PROOF usage # # @param makefile_path Path to the makefile that should be transformed # @param verbose <code>True</code> if verbose printout is requested def MakefileTransform( makefile_path, verbose ): if verbose: print " >>" print " >> Running PARHelpers.MakefileTransform" print " >>" # Read in the contents of the makefile: makefile = open( makefile_path, "r" ) contents = makefile.read() makefile.close() # Do the necessary changes: new_contents = re.sub( "\$\(SFRAME_DIR\)\/Makefile\.common", "Makefile.proof", contents ) # Write out the modified contents in the same file: makefile = open( makefile_path, "w" ) makefile.write( new_contents ) makefile.close() return ## Create a makefile fragment with the directives for PROOF usage # # @param makefile_path Path to the makefile that should be created # @param verbose <code>True</code> if verbose printout is requested def MakefileProof( makefile_path, verbose ): if verbose: print " >>" print " >> Running PARHelpers.MakefileProof" print " >>" makefile = open( makefile_path, "w" ) makefile.write( MakefileProofContent ) makefile.close() return ## Transform the contents of the specified source file for PROOF usage # # @param file_path Path to the source file that should be transformed def SourceTransform( file_path ): # Read in the contents of the source file: file = open( file_path, "r" ) contents = file.read() file.close() # Do the necessary changes: contents = re.sub( "core\/include", "SFrameCore/include", contents ) contents = re.sub( "plug\-ins\/include", "SFramePlugIns/include", contents ) # Write out the modified contents in the same file: file = open( file_path, "w" ) file.write( contents ) file.close() return ## Contents of the makefile for PROOF compilation MakefileProofContent = """MAKEFLAGS = --no-print-directory -r -s # Include the architecture definitions from the ROOT source: ARCH_LOC_1 := $(wildcard $(shell root-config --prefix)/test/Makefile.arch) ARCH_LOC_2 := $(wildcard $(shell root-config --prefix)/share/root/test/Makefile.arch) ARCH_LOC_3 := $(wildcard $(shell root-config --prefix)/share/doc/root/test/Makefile.arch) ARCH_LOC_4 := $(wildcard $(shell root-config --prefix)/etc/Makefile.arch) ARCH_LOC_5 := $(wildcard $(shell root-config --prefix)/etc/root/Makefile.arch) ifneq ($(strip $(ARCH_LOC_1)),) $(info Using $(ARCH_LOC_1)) include $(ARCH_LOC_1) else ifneq ($(strip $(ARCH_LOC_2)),) $(info Using $(ARCH_LOC_2)) include $(ARCH_LOC_2) else ifneq ($(strip $(ARCH_LOC_3)),) $(info Using $(ARCH_LOC_3)) include $(ARCH_LOC_3) else ifneq ($(strip $(ARCH_LOC_4)),) $(info Using $(ARCH_LOC_4)) include $(ARCH_LOC_4) else ifneq ($(strip $(ARCH_LOC_5)),) $(info Using $(ARCH_LOC_5)) include $(ARCH_LOC_5) else $(error Could not find Makefile.arch!) endif endif endif endif endif # Some compilation options VPATH += $(OBJDIR) $(SRCDIR) INCLUDES += -I./ -I../ CXXFLAGS += -Wall -Wno-overloaded-virtual -Wno-unused $(USERCXXFLAGS) # Set the locations of some files DICTHEAD = $(SRCDIR)/$(LIBRARY)_Dict.h DICTFILE = $(SRCDIR)/$(LIBRARY)_Dict.$(SrcSuf) DICTOBJ = $(OBJDIR)/$(LIBRARY)_Dict.$(ObjSuf) DICTLDEF = $(INCDIR)/$(LIBRARY)_LinkDef.h SKIPCPPLIST = $(DICTFILE) SKIPHLIST = $(DICTHEAD) $(DICTLDEF) SHLIBFILE = lib$(LIBRARY).$(DllSuf) UNAME = $(shell uname) # Set up the default targets default: shlib # List of all header and source files to build HLIST = $(filter-out $(SKIPHLIST),$(wildcard $(INCDIR)/*.h)) CPPLIST = $(filter-out $(SKIPCPPLIST),$(wildcard $(SRCDIR)/*.$(SrcSuf))) # List of all object files to build OLIST = $(patsubst %.$(SrcSuf),%.o,$(notdir $(CPPLIST))) # Implicit rule to compile all sources %.o : %.$(SrcSuf) @echo "Compiling $<" @mkdir -p $(OBJDIR) @$(CXX) $(CXXFLAGS) -c $< -o $(OBJDIR)/$(notdir $@) $(INCLUDES) # Rule to create the dictionary $(DICTFILE): $(HLIST) $(DICTLDEF) @echo "Generating dictionary $@" @$(shell root-config --exec-prefix)/bin/rootcint -f $(DICTFILE) -c -p $(INCLUDES) $^ # Rule to comile the dictionary $(DICTOBJ): $(DICTFILE) @echo "Compiling $<" @mkdir -p $(OBJDIR) $(CXX) $(CXXFLAGS) -c $(INCLUDES) -o $@ $< -include $(foreach var,$(notdir $(CPPLIST:.$(SrcSuf)=.d)),$(DEPDIR)/$(var)) $(DEPDIR)/%.d: %.$(SrcSuf) @mkdir -p $(DEPDIR) if test -f $< ; then \ echo "Making $(@F)"; \ $(SHELL) -ec '$(CPP) -MM $(CXXFLAGS) $(INCLUDES) $< | sed '\''/Cstd\/rw/d'\'' > $@'; \ fi # Rule to combine objects into a unix shared library $(SHLIBFILE): $(OLIST) $(DICTOBJ) @echo "Making shared library: $(SHLIBFILE)" @rm -f $(SHLIBFILE) ifneq (,$(findstring macosx,$(ARCH))) @$(LD) $(LDFLAGS) $(USERLDFLAGS) -dynamiclib -single_module -undefined dynamic_lookup $(addprefix $(OBJDIR)/,$(OLIST)) $(DICTOBJ) -o $(SHLIBFILE) else @$(LD) $(LDFLAGS) $(USERLDFLAGS) $(SOFLAGS) $(addprefix $(OBJDIR)/,$(OLIST)) $(DICTOBJ) -o $(SHLIBFILE) endif # Useful build targets shlib: $(SHLIBFILE) clean: rm -f $(DICTFILE) $(DICTHEAD) rm -f $(OBJDIR)/*.o rm -f $(SHLIBFILE) rm -f lib$(LIBRARY).so distclean: rm -rf $(OBJDIR) rm -f *~ rm -f $(INCDIR)/*~ rm -f $(SRCDIR)/*~ rm -f $(DICTFILE) $(DICTHEAD) rm -f $(DEPDIR)/*.d rm -f $(SHLIBFILE) rm -f lib$(LIBRARY).so .PHONY : shlib default clean """
{ "repo_name": "jpavel/cms-ucl-tau", "path": "SFrame/python/PARHelpers.py", "copies": "1", "size": "11519", "license": "mit", "hash": 2455119844852149000, "line_mean": 33.3850746269, "line_max": 146, "alpha_frac": 0.5945828631, "autogenerated": false, "ratio": 3.520476772616137, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46150596357161366, "avg_score": null, "num_lines": null }
# $Id: parseInput.py,v 1.2 2005/07/19 17:47:46 phoebusc Exp $ ## Parses input file of OscopeMsgs # Supports: # 1) Default TinyOS packets of OscopeMsgs # (with 10 samples or even 11 samples per packet) # 2) Telos packets of OscopeMsgs # 3) GGB dumped output # See PIRDataFormat.txt for details on these data formats # # "Commenting" in input files: # * OscopeMsg formats: ignores all lines that have less than 'offset' # bytes. Assumes these are Connection Strings, timestamps, # or other comments # * GGB format: ignores all lines without length of 8 'bytes' (space # separated columns) # PRECONDITION: all data on channel 0 (else will give warnings) # @param format value:'xsm', 'xsm_extraPkt', 'telos', 'ggb # @returns list of: # data dictionary (nodeID_seqNo,value) # nodeState dictionary (nodeID_seqNo,value) # value = 1 for 'initialized' node # can change to other values to indicate finished, etc. # minSeqNo dictionary (nodeID_seqNo,value) # maxSeqNo dictionary (nodeID_seqNo,value) def parseFile(format,filename): data = {} nodeState = {} minSeqNo = {} maxSeqNo = {} f = open(filename) pktData = f.readlines() f.close() if (format == 'xsm_extraPkt'): offset = 5 pktSamples = 11 OscopeMsgFormat = True elif (format == 'xsm'): offset = 5 pktSamples = 10 OscopeMsgFormat = True elif (format == 'telos'): offset = 10 pktSamples = 10 OscopeMsgFormat = True elif (format == 'ggb'): offset = 0 OscopeMsgFormat = False if OscopeMsgFormat: for i in range(0,len(pktData)): byteList = pktData[i].split() if len(byteList) > offset: nodeID = int(byteList[offset+1]+byteList[offset],16) if not(nodeState.has_key(nodeID)): nodeState[nodeID] = 1 minSeqNo[nodeID] = int('FFFF',16) maxSeqNo[nodeID] = 0 ## parse sequence numbers seqNo = int(byteList[offset+3]+byteList[offset+2],16) maxSeqNo[nodeID] = max(maxSeqNo[nodeID], seqNo) seqNo = seqNo - pktSamples # subtract pktSamples since the #seqNo is actually the last seqNo in the message minSeqNo[nodeID] = min(minSeqNo[nodeID], seqNo) ## check input on channel 0 chanNo = int(byteList[offset+5]+byteList[offset+4],16) if (chanNo != 0): print "WARNING: input data not from channel 0, from channel" + str(chanNo) print " File: " + filename + ", Line: " + str(i) ## parse data for j in range(offset+6, len(byteList), 2): value = byteList[j+1] + byteList[j] key = str(nodeID) + '_' + str(seqNo+((j-offset+6)/2)) data[key] = int(value, 16) else: #currently, defaults to GGB format for i in range(0,len(pktData)): byteList = pktData[i].split() if len(byteList) == 8: nodeID = 1 # should be from filename... fix later if not(nodeState.has_key(nodeID)): nodeState[nodeID] = 1 minSeqNo[nodeID] = int('FFFF',16) maxSeqNo[nodeID] = 0 ## parse sequence numbers seqNo = int(byteList[offset]) # first 'byte' is already in decimal format maxSeqNo[nodeID] = max(maxSeqNo[nodeID], seqNo) minSeqNo[nodeID] = min(minSeqNo[nodeID], seqNo) # should always be 1 ## clicker sequence number currently not used ## parse data value = byteList[6] + byteList[5] key = str(nodeID) + '_' + str(seqNo) data[key] = int(value, 16) return [data,nodeState,minSeqNo,maxSeqNo] # ## Testing Code # a = parseFile("xsm","samplefiles/XSM_11samplepktsInputData") # print "nodeState: " # print a[1] # print "minSeqNo: " # print a[2] # print "maxSeqNo: " # print a[3]
{ "repo_name": "fresskarma/tinyos-1.x", "path": "contrib/nestfe/nesc/apps/TestPIRDetectNoReg/parseInput.py", "copies": "2", "size": "4249", "license": "bsd-3-clause", "hash": -4905242507078528000, "line_mean": 38.3425925926, "line_max": 94, "alpha_frac": 0.549305719, "autogenerated": false, "ratio": 3.67560553633218, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006454833262151715, "num_lines": 108 }
""" Transforms related to document parts. """ __docformat__ = 'reStructuredText' import re import sys from docutils import nodes, utils from docutils.transforms import TransformError, Transform class SectNum(Transform): """ Automatically assigns numbers to the titles of document sections. It is possible to limit the maximum section level for which the numbers are added. For those sections that are auto-numbered, the "autonum" attribute is set, informing the contents table generator that a different form of the TOC should be used. """ default_priority = 710 """Should be applied before `Contents`.""" def apply(self): self.maxdepth = self.startnode.details.get('depth', sys.maxint) self.startvalue = self.startnode.details.get('start', 1) self.prefix = self.startnode.details.get('prefix', '') self.suffix = self.startnode.details.get('suffix', '') self.startnode.parent.remove(self.startnode) if self.document.settings.sectnum_xform: self.update_section_numbers(self.document) def update_section_numbers(self, node, prefix=(), depth=0): depth += 1 if prefix: sectnum = 1 else: sectnum = self.startvalue for child in node: if isinstance(child, nodes.section): numbers = prefix + (str(sectnum),) title = child[0] # Use &nbsp; for spacing: generated = nodes.generated( '', (self.prefix + '.'.join(numbers) + self.suffix + u'\u00a0' * 3), classes=['sectnum']) title.insert(0, generated) title['auto'] = 1 if depth < self.maxdepth: self.update_section_numbers(child, numbers, depth) sectnum += 1 class Contents(Transform): """ This transform generates a table of contents from the entire document tree or from a single branch. It locates "section" elements and builds them into a nested bullet list, which is placed within a "topic" created by the contents directive. A title is either explicitly specified, taken from the appropriate language module, or omitted (local table of contents). The depth may be specified. Two-way references between the table of contents and section titles are generated (requires Writer support). This transform requires a startnode, which which contains generation options and provides the location for the generated table of contents (the startnode is replaced by the table of contents "topic"). """ default_priority = 720 def apply(self): details = self.startnode.details if details.has_key('local'): startnode = self.startnode.parent.parent while not (isinstance(startnode, nodes.section) or isinstance(startnode, nodes.document)): # find the ToC root: a direct ancestor of startnode startnode = startnode.parent else: startnode = self.document self.toc_id = self.startnode.parent['ids'][0] if details.has_key('backlinks'): self.backlinks = details['backlinks'] else: self.backlinks = self.document.settings.toc_backlinks contents = self.build_contents(startnode) if len(contents): self.startnode.replace_self(contents) else: self.startnode.parent.parent.remove(self.startnode.parent) def build_contents(self, node, level=0): level += 1 sections = [sect for sect in node if isinstance(sect, nodes.section)] entries = [] autonum = 0 depth = self.startnode.details.get('depth', sys.maxint) for section in sections: title = section[0] auto = title.get('auto') # May be set by SectNum. entrytext = self.copy_and_filter(title) reference = nodes.reference('', '', refid=section['ids'][0], *entrytext) ref_id = self.document.set_id(reference) entry = nodes.paragraph('', '', reference) item = nodes.list_item('', entry) if ( self.backlinks in ('entry', 'top') and title.next_node(nodes.reference) is None): if self.backlinks == 'entry': title['refid'] = ref_id elif self.backlinks == 'top': title['refid'] = self.toc_id if level < depth: subsects = self.build_contents(section, level) item += subsects entries.append(item) if entries: contents = nodes.bullet_list('', *entries) if auto: contents['classes'].append('auto-toc') return contents else: return [] def copy_and_filter(self, node): """Return a copy of a title, with references, images, etc. removed.""" visitor = ContentsFilter(self.document) node.walkabout(visitor) return visitor.get_entry_text() class ContentsFilter(nodes.TreeCopyVisitor): def get_entry_text(self): return self.get_tree_copy().children def visit_citation_reference(self, node): raise nodes.SkipNode def visit_footnote_reference(self, node): raise nodes.SkipNode def visit_image(self, node): if node.hasattr('alt'): self.parent.append(nodes.Text(node['alt'])) raise nodes.SkipNode def ignore_node_but_process_children(self, node): raise nodes.SkipDeparture visit_interpreted = ignore_node_but_process_children visit_problematic = ignore_node_but_process_children visit_reference = ignore_node_but_process_children visit_target = ignore_node_but_process_children
{ "repo_name": "PatrickKennedy/Sybil", "path": "docutils/transforms/parts.py", "copies": "2", "size": "6145", "license": "bsd-2-clause", "hash": 3142189523887116300, "line_mean": 36.4695121951, "line_max": 78, "alpha_frac": 0.6087876322, "autogenerated": false, "ratio": 4.273296244784423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5882083876984423, "avg_score": null, "num_lines": null }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "spreeker/democracygame", "path": "external_apps/docutils-snapshot/docutils/parsers/rst/directives/parts.py", "copies": "10", "size": "4052", "license": "bsd-3-clause", "hash": -7043641712419857000, "line_mean": 31.9430894309, "line_max": 77, "alpha_frac": 0.6073543929, "autogenerated": false, "ratio": 4.265263157894736, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9872617550794737, "avg_score": null, "num_lines": null }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "rimbalinux/MSISDNArea", "path": "docutils/parsers/rst/directives/parts.py", "copies": "2", "size": "4175", "license": "bsd-3-clause", "hash": 2135020183837352700, "line_mean": 31.9430894309, "line_max": 77, "alpha_frac": 0.5894610778, "autogenerated": false, "ratio": 4.3264248704663215, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0013550135501355014, "num_lines": 123 }
""" Transforms related to document parts. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes from docutils.transforms import Transform class SectNum(Transform): """ Automatically assigns numbers to the titles of document sections. It is possible to limit the maximum section level for which the numbers are added. For those sections that are auto-numbered, the "autonum" attribute is set, informing the contents table generator that a different form of the TOC should be used. """ default_priority = 710 """Should be applied before `Contents`.""" def apply(self): self.maxdepth = self.startnode.details.get('depth', None) self.startvalue = self.startnode.details.get('start', 1) self.prefix = self.startnode.details.get('prefix', '') self.suffix = self.startnode.details.get('suffix', '') self.startnode.parent.remove(self.startnode) if self.document.settings.sectnum_xform: if self.maxdepth is None: self.maxdepth = sys.maxint self.update_section_numbers(self.document) else: # store details for eventual section numbering by the writer self.document.settings.sectnum_depth = self.maxdepth self.document.settings.sectnum_start = self.startvalue self.document.settings.sectnum_prefix = self.prefix self.document.settings.sectnum_suffix = self.suffix def update_section_numbers(self, node, prefix=(), depth=0): depth += 1 if prefix: sectnum = 1 else: sectnum = self.startvalue for child in node: if isinstance(child, nodes.section): numbers = prefix + (str(sectnum),) title = child[0] # Use &nbsp; for spacing: generated = nodes.generated( '', (self.prefix + '.'.join(numbers) + self.suffix + u'\u00a0' * 3), classes=['sectnum']) title.insert(0, generated) title['auto'] = 1 if depth < self.maxdepth: self.update_section_numbers(child, numbers, depth) sectnum += 1 class Contents(Transform): """ This transform generates a table of contents from the entire document tree or from a single branch. It locates "section" elements and builds them into a nested bullet list, which is placed within a "topic" created by the contents directive. A title is either explicitly specified, taken from the appropriate language module, or omitted (local table of contents). The depth may be specified. Two-way references between the table of contents and section titles are generated (requires Writer support). This transform requires a startnode, which contains generation options and provides the location for the generated table of contents (the startnode is replaced by the table of contents "topic"). """ default_priority = 720 def apply(self): try: # let the writer (or output software) build the contents list? toc_by_writer = self.document.settings.use_latex_toc except AttributeError: toc_by_writer = False details = self.startnode.details if 'local' in details: startnode = self.startnode.parent.parent while not (isinstance(startnode, nodes.section) or isinstance(startnode, nodes.document)): # find the ToC root: a direct ancestor of startnode startnode = startnode.parent else: startnode = self.document self.toc_id = self.startnode.parent['ids'][0] if 'backlinks' in details: self.backlinks = details['backlinks'] else: self.backlinks = self.document.settings.toc_backlinks if toc_by_writer: # move customization settings to the parent node self.startnode.parent.attributes.update(details) self.startnode.parent.remove(self.startnode) else: contents = self.build_contents(startnode) if len(contents): self.startnode.replace_self(contents) else: self.startnode.parent.parent.remove(self.startnode.parent) def build_contents(self, node, level=0): level += 1 sections = [sect for sect in node if isinstance(sect, nodes.section)] entries = [] autonum = 0 depth = self.startnode.details.get('depth', sys.maxint) for section in sections: title = section[0] auto = title.get('auto') # May be set by SectNum. entrytext = self.copy_and_filter(title) reference = nodes.reference('', '', refid=section['ids'][0], *entrytext) ref_id = self.document.set_id(reference) entry = nodes.paragraph('', '', reference) item = nodes.list_item('', entry) if ( self.backlinks in ('entry', 'top') and title.next_node(nodes.reference) is None): if self.backlinks == 'entry': title['refid'] = ref_id elif self.backlinks == 'top': title['refid'] = self.toc_id if level < depth: subsects = self.build_contents(section, level) item += subsects entries.append(item) if entries: contents = nodes.bullet_list('', *entries) if auto: contents['classes'].append('auto-toc') return contents else: return [] def copy_and_filter(self, node): """Return a copy of a title, with references, images, etc. removed.""" visitor = ContentsFilter(self.document) node.walkabout(visitor) return visitor.get_entry_text() class ContentsFilter(nodes.TreeCopyVisitor): def get_entry_text(self): return self.get_tree_copy().children def visit_citation_reference(self, node): raise nodes.SkipNode def visit_footnote_reference(self, node): raise nodes.SkipNode def visit_image(self, node): if node.hasattr('alt'): self.parent.append(nodes.Text(node['alt'])) raise nodes.SkipNode def ignore_node_but_process_children(self, node): raise nodes.SkipDeparture visit_interpreted = ignore_node_but_process_children visit_problematic = ignore_node_but_process_children visit_reference = ignore_node_but_process_children visit_target = ignore_node_but_process_children
{ "repo_name": "MER-GROUP/intellij-community", "path": "python/helpers/py2only/docutils/transforms/parts.py", "copies": "5", "size": "6947", "license": "apache-2.0", "hash": 973878429905803000, "line_mean": 37.8100558659, "line_max": 78, "alpha_frac": 0.6090398733, "autogenerated": false, "ratio": 4.304213135068154, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00038239815658222017, "num_lines": 179 }
""" Transforms related to document parts. """ __docformat__ = 'reStructuredText' import re import sys from docutils import nodes, utils from docutils.transforms import TransformError, Transform class SectNum(Transform): """ Automatically assigns numbers to the titles of document sections. It is possible to limit the maximum section level for which the numbers are added. For those sections that are auto-numbered, the "autonum" attribute is set, informing the contents table generator that a different form of the TOC should be used. """ default_priority = 710 """Should be applied before `Contents`.""" def apply(self): self.maxdepth = self.startnode.details.get('depth', None) self.startvalue = self.startnode.details.get('start', 1) self.prefix = self.startnode.details.get('prefix', '') self.suffix = self.startnode.details.get('suffix', '') self.startnode.parent.remove(self.startnode) if self.document.settings.sectnum_xform: if self.maxdepth is None: self.maxdepth = sys.maxint self.update_section_numbers(self.document) else: # store details for eventual section numbering by the writer self.document.settings.sectnum_depth = self.maxdepth self.document.settings.sectnum_start = self.startvalue self.document.settings.sectnum_prefix = self.prefix self.document.settings.sectnum_suffix = self.suffix def update_section_numbers(self, node, prefix=(), depth=0): depth += 1 if prefix: sectnum = 1 else: sectnum = self.startvalue for child in node: if isinstance(child, nodes.section): numbers = prefix + (str(sectnum),) title = child[0] # Use &nbsp; for spacing: generated = nodes.generated( '', (self.prefix + '.'.join(numbers) + self.suffix + u'\u00a0' * 3), classes=['sectnum']) title.insert(0, generated) title['auto'] = 1 if depth < self.maxdepth: self.update_section_numbers(child, numbers, depth) sectnum += 1 class Contents(Transform): """ This transform generates a table of contents from the entire document tree or from a single branch. It locates "section" elements and builds them into a nested bullet list, which is placed within a "topic" created by the contents directive. A title is either explicitly specified, taken from the appropriate language module, or omitted (local table of contents). The depth may be specified. Two-way references between the table of contents and section titles are generated (requires Writer support). This transform requires a startnode, which contains generation options and provides the location for the generated table of contents (the startnode is replaced by the table of contents "topic"). """ default_priority = 720 def apply(self): try: # let the writer (or output software) build the contents list? toc_by_writer = self.document.settings.use_latex_toc except AttributeError: toc_by_writer = False details = self.startnode.details if 'local' in details: startnode = self.startnode.parent.parent while not (isinstance(startnode, nodes.section) or isinstance(startnode, nodes.document)): # find the ToC root: a direct ancestor of startnode startnode = startnode.parent else: startnode = self.document self.toc_id = self.startnode.parent['ids'][0] if 'backlinks' in details: self.backlinks = details['backlinks'] else: self.backlinks = self.document.settings.toc_backlinks if toc_by_writer: # move customization settings to the parent node self.startnode.parent.attributes.update(details) self.startnode.parent.remove(self.startnode) else: contents = self.build_contents(startnode) if len(contents): self.startnode.replace_self(contents) else: self.startnode.parent.parent.remove(self.startnode.parent) def build_contents(self, node, level=0): level += 1 sections = [sect for sect in node if isinstance(sect, nodes.section)] entries = [] autonum = 0 depth = self.startnode.details.get('depth', sys.maxint) for section in sections: title = section[0] auto = title.get('auto') # May be set by SectNum. entrytext = self.copy_and_filter(title) reference = nodes.reference('', '', refid=section['ids'][0], *entrytext) ref_id = self.document.set_id(reference) entry = nodes.paragraph('', '', reference) item = nodes.list_item('', entry) if ( self.backlinks in ('entry', 'top') and title.next_node(nodes.reference) is None): if self.backlinks == 'entry': title['refid'] = ref_id elif self.backlinks == 'top': title['refid'] = self.toc_id if level < depth: subsects = self.build_contents(section, level) item += subsects entries.append(item) if entries: contents = nodes.bullet_list('', *entries) if auto: contents['classes'].append('auto-toc') return contents else: return [] def copy_and_filter(self, node): """Return a copy of a title, with references, images, etc. removed.""" visitor = ContentsFilter(self.document) node.walkabout(visitor) return visitor.get_entry_text() class ContentsFilter(nodes.TreeCopyVisitor): def get_entry_text(self): return self.get_tree_copy().children def visit_citation_reference(self, node): raise nodes.SkipNode def visit_footnote_reference(self, node): raise nodes.SkipNode def visit_image(self, node): if node.hasattr('alt'): self.parent.append(nodes.Text(node['alt'])) raise nodes.SkipNode def ignore_node_but_process_children(self, node): raise nodes.SkipDeparture visit_interpreted = ignore_node_but_process_children visit_problematic = ignore_node_but_process_children visit_reference = ignore_node_but_process_children visit_target = ignore_node_but_process_children
{ "repo_name": "rimbalinux/MSISDNArea", "path": "docutils/transforms/parts.py", "copies": "2", "size": "7160", "license": "bsd-3-clause", "hash": 3900566636396623400, "line_mean": 37.7777777778, "line_max": 78, "alpha_frac": 0.5946927374, "autogenerated": false, "ratio": 4.389944819129369, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5984637556529369, "avg_score": null, "num_lines": null }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.parsers.rst import Directive from docutils.parsers.rst import directives from docutils.transforms import parts class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) # the latex2e writer needs source and line for a warning: src, srcline = self.state_machine.get_source_and_line() topic.source = src topic.line = srcline - 1 if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "MichaelNedzelsky/intellij-community", "path": "python/helpers/py2only/docutils/parsers/rst/directives/parts.py", "copies": "5", "size": "4241", "license": "apache-2.0", "hash": -6302639254382275000, "line_mean": 32.3937007874, "line_max": 77, "alpha_frac": 0.6078755011, "autogenerated": false, "ratio": 4.23253493013972, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.734041043123972, "avg_score": null, "num_lines": null }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) # the latex2e writer needs source and line for a warning: src, srcline = self.state_machine.get_source_and_line() topic.source = src topic.line = srcline - 1 if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "holmes/intellij-community", "path": "python/helpers/docutils/parsers/rst/directives/parts.py", "copies": "41", "size": "4241", "license": "apache-2.0", "hash": 5813985434273503000, "line_mean": 32.3937007874, "line_max": 77, "alpha_frac": 0.6078755011, "autogenerated": false, "ratio": 4.23253493013972, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015748031496062994, "num_lines": 127 }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code, document.reporter) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) # the latex2e writer needs source and line for a warning: src, srcline = self.state_machine.get_source_and_line() topic.source = src topic.line = srcline - 1 if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "cuongthai/cuongthai-s-blog", "path": "docutils/parsers/rst/directives/parts.py", "copies": "2", "size": "4402", "license": "bsd-3-clause", "hash": -3910978530612231000, "line_mean": 32.6614173228, "line_max": 77, "alpha_frac": 0.5851885507, "autogenerated": false, "ratio": 4.328416912487709, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0013123359580052493, "num_lines": 127 }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.parsers.rst import Directive from docutils.parsers.rst import directives from docutils.transforms import parts class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code, document.reporter) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) # the latex2e writer needs source and line for a warning: topic.source, topic.line = self.state_machine.get_source_and_line() topic.line -= 1 if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "JetBrains/intellij-community", "path": "python/helpers/py3only/docutils/parsers/rst/directives/parts.py", "copies": "44", "size": "4251", "license": "apache-2.0", "hash": 7492878561025526000, "line_mean": 32.7380952381, "line_max": 77, "alpha_frac": 0.6033874382, "autogenerated": false, "ratio": 4.280966767371601, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015873015873015873, "num_lines": 126 }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class Contents(Directive): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, Contents.backlinks_values) if value == 'none': return None else: return value optional_arguments = 1 final_argument_whitespace = True option_spec = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def run(self): if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)): raise self.error('The "%s" directive may not be used within ' 'topics or body elements.' % self.name) document = self.state_machine.document language = languages.get_language(document.settings.language_code, document.reporter) if self.arguments: title_text = self.arguments[0] text_nodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if 'local' in self.options: title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += self.options.get('class', []) # the latex2e writer needs source and line for a warning: topic.source, topic.line = self.state_machine.get_source_and_line() topic.line -= 1 if 'local' in self.options: topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=self.block_text) pending.details.update(self.options) document.note_pending(pending) topic += pending return [topic] + messages class Sectnum(Directive): """Automatic section numbering.""" option_spec = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def run(self): pending = nodes.pending(parts.SectNum) pending.details.update(self.options) self.state_machine.document.note_pending(pending) return [pending] class Header(Directive): """Contents of document header.""" has_content = True def run(self): self.assert_has_content() header = self.state_machine.document.get_decoration().get_header() self.state.nested_parse(self.content, self.content_offset, header) return [] class Footer(Directive): """Contents of document footer.""" has_content = True def run(self): self.assert_has_content() footer = self.state_machine.document.get_decoration().get_footer() self.state.nested_parse(self.content, self.content_offset, footer) return []
{ "repo_name": "sabi0/intellij-community", "path": "python/helpers/py2only/docutils/parsers/rst/directives/parts.py", "copies": "136", "size": "4251", "license": "apache-2.0", "hash": -1130091255926002700, "line_mean": 32.7380952381, "line_max": 77, "alpha_frac": 0.6033874382, "autogenerated": false, "ratio": 4.280966767371601, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015873015873015873, "num_lines": 126 }
from twisted.internet import reactor from twisted.spread import pb from twisted.internet.error import CannotListenError from peloton.adapters import AbstractPelotonAdapter from peloton.coreio import PelotonRequestInterface from peloton.coreio import PelotonInternodeInterface from peloton.events import RemoteEventHandler from peloton.exceptions import PelotonError class PelotonPBAdapter(AbstractPelotonAdapter, pb.Root): """ The primary client adapter for Peloton is the Python Twisted PB RPC mechanism. This provides the most complete and sophisticated interface to the Peloton grid. This adapter is just a gate-keeper though; anything obtaining this must gain trust and obtain a Referenceable through which real work can be done. """ def __init__(self, kernel): AbstractPelotonAdapter.__init__(self, kernel, 'TwistedPB') self.logger = self.kernel.logger def start(self): """ In this startup the adapter seeks to bind to a port. It obtains the host/port to which to bind from the kernel profile, but it may, according to whether the 'anyport' switch is set or not, seek an alternative port should its chosen target be bound by another application. """ interface,port = self.kernel.settings.bind.split(':') port = int(port) svr = pb.PBServerFactory(self) while True: try: self.connection = reactor.listenTCP(port, svr, interface=interface) self.kernel.profile['bind']= "%s:%d" % (interface, port) self.kernel.profile['bind_interface'] = interface self.kernel.profile['bind_port'] = port break except CannotListenError: if self.kernel.settings.anyport == True: port += 1 else: raise RuntimeError("Cannot bind to port %d" % port) except Exception: self.logger.exception("Could not connect %s" % self.adapterName) self.logger.info("Bound to %s:%d" % (interface, port)) def _stopped(self, x): """ Handler called when reactor has stopped listening to this protocol's port.""" pass def stop(self): """ Close down this adapter. """ d = self.connection.stopListening() d.addCallback(self._stopped) def remote_registerPSC(self, token): """ A remote PSC will call registerPSC with a token encrypted with the domain key. Provided this decrypts we know the remote PSC is permitted to join in this domain. the remotePSC is a remote instance of PelotonGridAdapter which provides methods for inter-PSC work. @todo: it may be that the token can be included in the remotePSC using copyable type stuff. """ self.logger.info("RegisterPSC %s: ref returned with NO VALIDATION" % token) ref = PelotonInternodeAdapter(self.kernel, token) return ref def remote_registerWorker(self, worker, token): """ A worker registers by sending a KernelInterface referenceable and a token. The token was passed to the worker generator and is used simply to verify that this is indeed a valid and wanted contact.""" self.logger.info("Starting worker, token=%s NOT VALIDATED" % token) serviceName, publishedName, runtimeConfig = self.kernel.addWorker(worker, token) pwa = PelotonWorkerAdapter(self, serviceName, self.kernel) worker.checkBeat = pwa.checkBeat workerInfo = { 'pwa' : pwa, 'serviceName' : serviceName, 'publishedName' : publishedName, 'runtimeConfig' : runtimeConfig, 'loglevel' : self.kernel.settings.loglevel, 'logdir' : self.kernel.settings.logdir, 'servicePath' : self.kernel.settings.servicepath, } return workerInfo def remote_login(self, clientObj): """ Login to Peloton. The clientObj contains the credentials to be used. Returns a PelotonClientAdapter""" return PelotonClientAdapter(self.kernel, clientObj) class PelotonInternodeAdapter(pb.Referenceable): """ Used to call between PSCs. """ def __init__(self, kernel, peerGUID): self.requestInterface = PelotonInternodeInterface(kernel) self.logger = kernel.logger self.peerGUID = peerGUID self.kernel = kernel def remote_relayCall(self, service, method, *args, **kwargs): """ Relay a method call between PSCs. """ return self.requestInterface.public_relayCall(self.peerGUID, service, method, *args, **kwargs) def remote_getInterface(self, name): """ Return the named interface to a plugin. """ return self.kernel.getCallable(name) class PelotonClientAdapter(pb.Referenceable): """ Referenceable used by client to call methods on the PSC. """ def __init__(self, kernel, clientObj): self.kernel = kernel self.dispatcher = kernel.dispatcher self.routingTable = kernel.routingTable self.requestInterface = PelotonRequestInterface(kernel) self.logger = kernel.logger self.clientObj = clientObj self.eventHandlers=[] def remote_call(self, service, method, *args, **kwargs): """ Make a call to the specified service.method and return the result.""" return self.requestInterface.public_call(self.clientObj, 'raw', service, method, args, kwargs) def remote_post(self, service, method, *args, **kwargs): """ Put a call on the call queue for later execution. Do not return result to client; this call will execute regardless of what the client does subsequently. """ raise NotImplementedError def remote_postLater(self, delay_seconds, service, method, *args, **kwargs): """ Post call onto the call queue after a delay of delay_seconds. """ raise NotImplementedError def remote_postAt(self, dateTime, service, method, *args, **kwargs): """ Post call onto the call queue at some future time. """ raise NotImplementedError def remote_fireEvent(self, key, exchange='events', **kwargs): """ Fire an event onto the bus. """ self.dispatcher.fireEvent(key, exchange, **kwargs) def remote_register(self, key, handler, exchange='events'): """ Register to receive events with the given handler. Handler must be a Referenceable providing remote_eventReceived.""" handler = RemoteEventHandler(handler) self.eventHandlers.append(handler) self.dispatcher.register(key, handler, exchange) def remote_deregister(self, handler): """ De-register handler as a listener. """ for h in self.eventHandlers: if h.remoteHandler == handler: handler = h break else: # no handler registered self.logger.error("Attempt to de-register handler for event that is not registered.") return self.dispatcher.deregister(handler) self.eventHandlers.remove(handler) def remote_getPSCProfile(self, guid=None): """ Returns the serialised profile for the referenced PSC or self if guid is None. """ if not guid: return repr(self.kernel.profile) else: try: return repr(self.routingTable.pscByGUID[guid].profile) except KeyError: raise PelotonError("%s is unknown" % guid) def remote_getRegisteredExchanges(self): """ Return a list of event exchanges registered in the dispatcher. """ return self.dispatcher.getRegisteredExchanges() class PelotonWorkerAdapter(pb.Referenceable): """ Interface by which a worker may invoke actions on the kernel. """ def __init__(self, name, pscRef, kernel): self.name = name # each time the worker calls, this sets to zero # each time the PSC checks it increments the value by # one... if the value hits a threshold, e.g. 5, the # worker is considered dead. self.heartBeat = 0 self.kernel = kernel self.pscRef = pscRef self.eventHandlers = [] def remote_notifyClosedown(self): """ Called when the worker is closing down. """ pass def remote_fireEvent(self, key, exchange, **kwargs): """ Fire an event onto the bus. """ self.kernel.dispatcher.fireEvent(key, exchange, **kwargs) def remote_register(self, key, handler, exchange='events'): """ Register to receive events with the given handler. Handler must be a Referenceable providing remote_eventReceived.""" handler = RemoteEventHandler(handler) self.eventHandlers.append(handler) self.kernel.dispatcher.register(key, handler, exchange) def remote_deregister(self, handler): """ De-register handler as a listener. """ for h in self.eventHandlers: if h.remoteHandler == handler: handler = h break else: # no handler registered self.logger.error("Attempt to de-register handler for event that is not registered.") return self.kernel.dispatcher.deregister(handler) self.eventHandlers.remove(handler) def remote_heartBeat(self): """ Called by the client to provide proof of life.""" self.heartBeat = 0 def checkBeat(self, threshold=5): """ Called from the PSC to check whether the worker is OK. the heartBeat counter is incremented. If the counter exceeds the threshold value (default 5) checkBeat returns False, otherwise returns True. """ self.heartBeat += 1 return self.heartBeat <= threshold def remote_serviceStartOK(self, version): """ Called to indicate safe start of service requested. """ self.kernel.logger.info("Worker reports start OK for %s %s" % (self.name, version)) def remote_serviceStartFailed(self, ex): """ Called with exception if service failed to start. """ self.kernel.logger.info("Worker reports start failed for %s : %s" % (self.name, ex))
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/adapters/pb.py", "copies": "1", "size": "10468", "license": "bsd-3-clause", "hash": 3356340066919036000, "line_mean": 41.0441767068, "line_max": 102, "alpha_frac": 0.6479747803, "autogenerated": false, "ratio": 4.318481848184819, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5466456628484818, "avg_score": null, "num_lines": null }
# $Id: pcap.py 371 2006-06-06 12:18:12Z dugsong $ """Libpcap file format.""" import sys, time import dpkt TCPDUMP_MAGIC = 0xa1b2c3d4L PMUDPCT_MAGIC = 0xd4c3b2a1L PCAP_VERSION_MAJOR = 2 PCAP_VERSION_MINOR = 4 DLT_NULL = 0 DLT_EN10MB = 1 DLT_EN3MB = 2 DLT_AX25 = 3 DLT_PRONET = 4 DLT_CHAOS = 5 DLT_IEEE802 = 6 DLT_ARCNET = 7 DLT_SLIP = 8 DLT_PPP = 9 DLT_FDDI = 10 # XXX - Linux DLT_LINUX_SLL = 113 # XXX - OpenBSD DLT_PFLOG = 117 DLT_PFSYNC = 18 if sys.platform.find('openbsd') != -1: DLT_LOOP = 12 DLT_RAW = 14 else: DLT_LOOP = 108 DLT_RAW = 12 dltoff = { DLT_NULL:4, DLT_EN10MB:14, DLT_IEEE802:22, DLT_ARCNET:6, DLT_SLIP:16, DLT_PPP:4, DLT_FDDI:21, DLT_PFLOG:48, DLT_PFSYNC:4, DLT_LOOP:4, DLT_RAW:0, DLT_LINUX_SLL:16 } class PktHdr(dpkt.Packet): """pcap packet header.""" __hdr__ = ( ('tv_sec', 'I', 0), ('tv_usec', 'I', 0), ('caplen', 'I', 0), ('len', 'I', 0), ) class LEPktHdr(PktHdr): __byte_order__ = '<' class FileHdr(dpkt.Packet): """pcap file header.""" __hdr__ = ( ('magic', 'I', TCPDUMP_MAGIC), ('v_major', 'H', PCAP_VERSION_MAJOR), ('v_minor', 'H', PCAP_VERSION_MINOR), ('thiszone', 'I', 0), ('sigfigs', 'I', 0), ('snaplen', 'I', 1500), ('linktype', 'I', 1), ) class LEFileHdr(FileHdr): __byte_order__ = '<' class Writer(object): """Simple pcap dumpfile writer.""" def __init__(self, fileobj, snaplen=1500, linktype=DLT_EN10MB): self.__f = fileobj fh = FileHdr(snaplen=snaplen, linktype=linktype) self.__f.write(str(fh)) def writepkt(self, pkt, ts=None): if ts is None: ts = time.time() s = str(pkt) n = len(s) ph = PktHdr(tv_sec=int(ts), tv_usec=int((int(ts) - float(ts)) * 1000000.0), caplen=n, len=n) self.__f.write(str(ph)) self.__f.write(s) def close(self): self.__f.close() class Reader(object): """Simple pypcap-compatible pcap file reader.""" def __init__(self, fileobj): self.name = fileobj.name self.fd = fileobj.fileno() self.__f = fileobj buf = self.__f.read(FileHdr.__hdr_len__) self.__fh = FileHdr(buf) self.__ph = PktHdr if self.__fh.magic == PMUDPCT_MAGIC: self.__fh = LEFileHdr(buf) self.__ph = LEPktHdr elif self.__fh.magic != TCPDUMP_MAGIC: raise ValueError, 'invalid tcpdump header' self.snaplen = self.__fh.snaplen self.dloff = dltoff[self.__fh.linktype] self.filter = '' def fileno(self): return self.fd def datalink(self): return self.__fh.linktype def setfilter(self, value, optimize=1): return NotImplementedError def readpkts(self): return list(self) def dispatch(self, cnt, callback, *args): if cnt > 0: for i in range(cnt): ts, pkt = self.next() callback(ts, pkt, *args) else: for ts, pkt in self: callback(ts, pkt, *args) def loop(self, callback, *args): self.dispatch(0, callback, *args) def __iter__(self): self.__f.seek(FileHdr.__hdr_len__) while 1: buf = self.__f.read(PktHdr.__hdr_len__) if not buf: break hdr = self.__ph(buf) buf = self.__f.read(hdr.caplen) yield (hdr.tv_sec + (hdr.tv_usec / 1000000.0), buf)
{ "repo_name": "MercenaryLogic/StompingGround", "path": "stompingground/dpkt/pcap.py", "copies": "1", "size": "3665", "license": "mit", "hash": -6848304551501262000, "line_mean": 25.3669064748, "line_max": 75, "alpha_frac": 0.5129604366, "autogenerated": false, "ratio": 2.9556451612903225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39686055978903223, "avg_score": null, "num_lines": null }
''' Created on 20. okt. 2009 @author: levin ''' from math import * import SEMBA as S #Create empty dictionaries to load emission data in Vehicle_Types = {} def create_vehicle_list(): for k,v in S.H_PC.items(): k=0 Vehicle_Types[v[0]]= v[2] +" "+ v[3]+" "+v[4] def CreatePC(): S.load_PC() S.load_PCGradient() create_vehicle_list() def findGrade(gradient,TrafficSituation): """ Find gradent value for lookuptable Finds the correct gradient value for lookup based on road category and gadient. Three traffic situations exist: urban road motorway """ g = 999999 if gradient <= -9 : g = -10 elif gradient <= -7 and gradient > -9 : g = -8 elif gradient <= -5 and gradient > -7 : g = -6 elif gradient <= -3 and gradient > -5 : g = -4 elif gradient <= -1 and gradient > -3 : g = -2 elif gradient <= 1 and gradient > -1 : g = 0 elif gradient <= 3 and gradient > 1 : g = 2 elif gradient <= 5 and gradient > 3 : g = 4 elif gradient <= 7 and gradient > 5 : g = 6 elif gradient <= 9 and gradient > 7 : g = 8 elif gradient > 9 : g = 10 if TrafficSituation =='urban' or TrafficSituation =='motorway': #limits road gradients to supported gradients if g < -6 : g = -6 if g > 6 : g = 6 return g def CalculatePC(PCID, Component, Speed, Gradient, Engine, TrafficSituation): """ Calculation of emissions from private cars UNITS: Speed km/h Gradient 0.06 is 6% Emission calculated is g/km Fuel is calculated from CO2 emissions by factors from SFT, Norway Maximum speed is 125 km/h Engine size: PETROL small < 1.4 liters medium 1.4 -> 2.0 liters large >2.0 liters DIESEL medium <2.0 liters large >2.0 liters """ WarningText = [] CalculateFCfromCO2 = False #Finds the correct gradient Gradient = findGrade(Gradient,TrafficSituation) if Component == "FC": Component = "CO2" CalculateFCfromCO2 = True if not (Component == "C02" or Component == "FC") : Engine = 'all' if Speed >= 6: #Get Data from the PC dictionary key = str(PCID) + "_" + Component + "_" + Engine value = S.H_PC[key] data = value VehicleID = data[0] EmissionComponent = data[1] FuelType = data[2] EngineSize = data[3] EuroClass = data[4] EquationType = data[5] Order = data[6] a0 = float(data[7]) a1 = float(data[8]) a2 = float(data[9]) a3 = float(data[10]) a4 = float(data[11]) a5 = float(data[12]) Emission = -1 if EquationType == 'Polyn.': Emission = float(a0) + \ float(a1) * float(Speed) + \ float(a2) * pow(float(Speed), 2) + \ float(a3) * pow(float(Speed), 3) + \ float(a4) * pow(float(Speed), 4) + \ float(a5) * pow(float(Speed), 5) if EquationType == 'Power': Emission = a0 * pow(Speed, a1) if CalculateFCfromCO2: if FuelType == "DIESEL": Emission = Emission / 3.18 WarningText.append("Fuel Calculated from CO2 emission factor 3.18") if FuelType == "PETROL": Emission = Emission / 3.13 WarningText.append("Fuel Calculated from CO2 emission factor 3.13") #Her ligger feilsjekkingsrutiner if Speed > 125 : WarningText.append("Emission Function used outside valid area") if (len(WarningText) == 0): WarningText.append("No Warnings") if Speed < 6: Emission = 0 WarningText.append("Speed Under 6kmh") #Here comes correction for gradient corrFactor = 0 GradeKey = EuroClass + "_" + TrafficSituation + "_" + str(Gradient) value = S.H_PCGrade[GradeKey] if FuelType == 'PETROL': if Component == 'CO': corrFactor = value[3] if Component == 'HC': corrFactor = value[4] if Component == 'NOx': corrFactor = value[5] if Component == 'FC': corrFactor = value[6] if Component == 'CO2': corrFactor = value[6] if Component == 'PM': corrFactor = 1 # ARTEMIS does not correct PM for gasoline for grades elif FuelType == 'DIESEL': if Component == 'CO': corrFactor = value[7] if Component == 'HC': corrFactor = value[8] if Component == 'NOx': corrFactor = value[9] if Component == 'PM': corrFactor = value[10] if Component == 'FC': corrFactor = value[11] if Component == 'CO2': corrFactor = value[11] CorrectedEmission = float(Emission) * float(corrFactor) egps = S.Convert_gpkm_to_gps(CorrectedEmission, Speed) return CorrectedEmission, "g/km", egps[0], egps[1], WarningText def ListTypes(): """ Lists all heavy duty vehicles available in the dataset that is loaded. """ #Function to sort as integers def compare(a, b): return cmp(int(a), int(b)) # compare as integers keys = Vehicle_Types.keys() keys.sort(compare) print "Private car ID ; Description" for key in keys: print str(key)+ ' ; '+ Vehicle_Types[key] ###########____Load Data____################## CreatePC() #test segment for debuging purposes if __name__ == "__main__": import matplotlib.pyplot as plt #@UnresolvedImport a = [] b = [] c = [] d = [] e = [] for i in range(6, 120): b.append(i) #def CalculateHDV(HDVID, Component, Speed, Gradient, Load): a.append(CalculatePC(4,"FC",i,0.02,all,"urban")[0]) c.append(CalculatePC(4,"FC",i,0,all,"urban")[0]) plt.plot(b, a) plt.plot(b, c) #plt.plot(b, c,label='Diesel Euro 4') #leg = plt.legend(loc=1) #for t in leg.get_texts(): # t.set_fontsize('x-small') # the legend text fontsize #plt.axis(ymin=0) #plt.grid(True) plt.ylabel('Fuel consumption Liter/10km') plt.xlabel('Vehicle average speed') plt.title('SEMBA PC Vehicle fuel consumption') plt.ylim(ymin=0) plt.show() #PCID, Component, Speed, Gradient, Engine, TrafficSituation print CalculatePC(3,"FC",100,0,all,"urban")
{ "repo_name": "tomasle/semba", "path": "SEMBA/PC.py", "copies": "1", "size": "6038", "license": "bsd-2-clause", "hash": 1820447009696073500, "line_mean": 25.252173913, "line_max": 76, "alpha_frac": 0.6015236833, "autogenerated": false, "ratio": 3.1349948078920042, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4236518491192004, "avg_score": null, "num_lines": null }
""" Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.parsers import rst from docutils.readers import standalone from docutils.transforms import peps, frontmatter class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') def get_transforms(self): transforms = standalone.Reader.get_transforms(self) # We have PEP-specific frontmatter handling. transforms.remove(frontmatter.DocTitle) transforms.remove(frontmatter.SectionSubTitle) transforms.remove(frontmatter.DocInfo) transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes]) return transforms settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=1, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
{ "repo_name": "MichaelNedzelsky/intellij-community", "path": "python/helpers/py2only/docutils/readers/pep.py", "copies": "5", "size": "1535", "license": "apache-2.0", "hash": 1071093278285077100, "line_mean": 31.6595744681, "line_max": 75, "alpha_frac": 0.674267101, "autogenerated": false, "ratio": 3.8959390862944163, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 47 }
""" Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.readers import standalone from docutils.transforms import peps, references, misc, frontmatter from docutils.parsers import rst class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') def get_transforms(self): transforms = standalone.Reader.get_transforms(self) # We have PEP-specific frontmatter handling. transforms.remove(frontmatter.DocTitle) transforms.remove(frontmatter.SectionSubTitle) transforms.remove(frontmatter.DocInfo) transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes]) return transforms settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=1, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
{ "repo_name": "Distrotech/intellij-community", "path": "python/helpers/docutils/readers/pep.py", "copies": "61", "size": "1554", "license": "apache-2.0", "hash": -5672985877778856000, "line_mean": 31.375, "line_max": 75, "alpha_frac": 0.675032175, "autogenerated": false, "ratio": 3.9045226130653266, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 48 }
""" Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.readers import standalone from docutils.transforms import peps, references, misc, frontmatter from docutils.parsers import rst class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') def get_transforms(self): transforms = standalone.Reader.get_transforms(self) # We have PEP-specific frontmatter handling. transforms.remove(frontmatter.DocTitle) transforms.remove(frontmatter.SectionSubTitle) transforms.remove(frontmatter.DocInfo) transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes]) return transforms settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=1, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
{ "repo_name": "rimbalinux/MSISDNArea", "path": "docutils/readers/pep.py", "copies": "2", "size": "1602", "license": "bsd-3-clause", "hash": 4833572402919962000, "line_mean": 31.375, "line_max": 75, "alpha_frac": 0.6548064919, "autogenerated": false, "ratio": 3.9653465346534653, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5620153026553465, "avg_score": null, "num_lines": null }
""" Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.parsers import rst from docutils.readers import standalone from docutils.transforms import peps, frontmatter class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') def get_transforms(self): transforms = standalone.Reader.get_transforms(self) # We have PEP-specific frontmatter handling. transforms.remove(frontmatter.DocTitle) transforms.remove(frontmatter.SectionSubTitle) transforms.remove(frontmatter.DocInfo) transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes]) return transforms settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=True, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
{ "repo_name": "GunoH/intellij-community", "path": "python/helpers/py3only/docutils/readers/pep.py", "copies": "44", "size": "1536", "license": "apache-2.0", "hash": -6169440003144018000, "line_mean": 31.6808510638, "line_max": 75, "alpha_frac": 0.6744791667, "autogenerated": false, "ratio": 3.9083969465648853, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 47 }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import os import re import time from docutils import DataError from docutils import nodes, utils, languages from docutils.transforms import Transform from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://svn.python.org/view/*checkout*' '/peps/trunk/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "Soya93/Extract-Refactoring", "path": "python/helpers/py2only/docutils/transforms/peps.py", "copies": "5", "size": "10957", "license": "apache-2.0", "hash": -699088058678748200, "line_mean": 35.0427631579, "line_max": 79, "alpha_frac": 0.5321712147, "autogenerated": false, "ratio": 4.248545948041877, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00043895144485401596, "num_lines": 304 }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://svn.python.org/view/*checkout*' '/peps/trunk/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "rimbalinux/LMD3", "path": "docutils/transforms/peps.py", "copies": "2", "size": "11305", "license": "bsd-3-clause", "hash": -8322641547668679000, "line_mean": 35.1875, "line_max": 79, "alpha_frac": 0.5192392747, "autogenerated": false, "ratio": 4.336401994629843, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00042786280435149404, "num_lines": 304 }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import os import re import time from docutils import DataError from docutils import nodes, utils, languages from docutils.transforms import Transform from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://svn.python.org/view/*checkout*' '/peps/trunk/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code, self.document.reporter) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "apixandru/intellij-community", "path": "python/helpers/py3only/docutils/transforms/peps.py", "copies": "44", "size": "11021", "license": "apache-2.0", "hash": -7752096150628550000, "line_mean": 35.1344262295, "line_max": 79, "alpha_frac": 0.5307140913, "autogenerated": false, "ratio": 4.263442940038685, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://svn.python.org/view/*checkout*' '/peps/trunk/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code, self.document.reporter) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "cuongthai/cuongthai-s-blog", "path": "docutils/transforms/peps.py", "copies": "2", "size": "11370", "license": "bsd-3-clause", "hash": -4548867373509582300, "line_mean": 35.2786885246, "line_max": 79, "alpha_frac": 0.5178540018, "autogenerated": false, "ratio": 4.349655700076511, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5867509701876511, "avg_score": null, "num_lines": null }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://hg.python.org' '/peps/file/default/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(r',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code, self.document.reporter) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "achang97/YouTunes", "path": "lib/python2.7/site-packages/docutils/transforms/peps.py", "copies": "10", "size": "11056", "license": "mit", "hash": 602424495491174800, "line_mean": 35.2491803279, "line_max": 79, "alpha_frac": 0.5320188133, "autogenerated": false, "ratio": 4.263787119166988, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9795805932466989, "avg_score": null, "num_lines": null }
# $Id: pim.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Protocol Independent Multicast.""" from __future__ import absolute_import from . import dpkt from .decorators import deprecated class PIM(dpkt.Packet): """Protocol Independent Multicast. TODO: Longer class information.... Attributes: __hdr__: Header fields of PIM. TODO. """ __hdr__ = ( ('_v_type', 'B', 0x20), ('rsvd', 'B', 0), ('sum', 'H', 0) ) @property def v(self): return self._v_type >> 4 @v.setter def v(self, v): self._v_type = (v << 4) | (self._v_type & 0xf) @property def type(self): return self._v_type & 0xf @type.setter def type(self, type): self._v_type = (self._v_type & 0xf0) | type def __bytes__(self): if not self.sum: self.sum = dpkt.in_cksum(dpkt.Packet.__bytes__(self)) return dpkt.Packet.__bytes__(self) def test_pim(): pimdata = PIM(b'\x20\x00\x9f\xf4\x00\x01\x00\x02\x00\x69') assert pimdata.v == 2 assert pimdata.type == 0 # test setters pimdata.v = 3 pimdata.type = 1 assert bytes(pimdata) == b'\x31\x00\x9f\xf4\x00\x01\x00\x02\x00\x69'
{ "repo_name": "smutt/dpkt", "path": "dpkt/pim.py", "copies": "3", "size": "1240", "license": "bsd-3-clause", "hash": -3314260106456645600, "line_mean": 21.5454545455, "line_max": 72, "alpha_frac": 0.5508064516, "autogenerated": false, "ratio": 2.857142857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4907949308742857, "avg_score": null, "num_lines": null }
# $Id: pim.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Protocol Independent Multicast.""" import dpkt from decorators import deprecated class PIM(dpkt.Packet): __hdr__ = ( ('_v_type', 'B', 0x20), ('rsvd', 'B', 0), ('sum', 'H', 0) ) @property def v(self): return self._v_type >> 4 @v.setter def v(self, v): self._v_type = (v << 4) | (self._v_type & 0xf) @property def type(self): return self._v_type & 0xf @type.setter def type(self, type): self._v_type = (self._v_type & 0xf0) | type # Deprecated methods, will be removed in the future # ================================================= @deprecated('v') def _get_v(self): return self.v @deprecated('v') def _set_v(self, v): self.v = v @deprecated('type') def _get_type(self): return self.type @deprecated('type') def _set_type(self, type): self.type = type # ================================================= def __str__(self): if not self.sum: self.sum = dpkt.in_cksum(dpkt.Packet.__str__(self)) return dpkt.Packet.__str__(self)
{ "repo_name": "hexcap/dpkt", "path": "dpkt/pim.py", "copies": "6", "size": "1185", "license": "bsd-3-clause", "hash": 3446851758194239500, "line_mean": 22.7, "line_max": 63, "alpha_frac": 0.4886075949, "autogenerated": false, "ratio": 3.3380281690140845, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6826635763914085, "avg_score": null, "num_lines": null }
# $Id: Pin.py,v 1.1 2017/08/27 00:40:41 tyamamot Exp $ from Module import * # Extpin is the special call only for inputs and outputs of class Pin #class Extpin: # def get_name(self): # return "" class Pin: def __init__(self, name, module, inout): self.name = name self.module = module self.inout = inout self.width = settings.box_width / 2 self.height = settings.pin_y_pitch * 1.5 self.external_pin = False self.tag = None #if self.inout == "input": # self.inputs = Extpin() # print "Pin.__init__(): module=", name, module.name #if self.inout == "output": # self.outputs = Extpin() def set_is_external_pin(self): self.external_pin = True def get_name(self): return self.name def get_inout_type(self): return self.inout def get_module(self): return self.module def is_external_pin(self): return self.external_pin def is_external_input(self): return self.inout == settings.tag_input def is_external_output(self): return self.inout == settings.tag_output def is_input(self): return self.inout == settings.tag_input def is_output(self): return self.inout == settings.tag_output # # methodes for instance drawing # def get_height(self): return self.height def get_tag(self): if self.tag == None: self.tag = settings.my_design.add_instance_tag(self) settings.instance_tag_count += 1 return self.tag #def set_module(self): # self.module = Module() # retrun self.module
{ "repo_name": "tyamamot5/Verilog-netlist-viewer", "path": "Pin.py", "copies": "1", "size": "1702", "license": "apache-2.0", "hash": -7073108229787554000, "line_mean": 22.9718309859, "line_max": 69, "alpha_frac": 0.5787309048, "autogenerated": false, "ratio": 3.5311203319502074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9586855021913293, "avg_score": 0.004599242967382841, "num_lines": 71 }
# $Id: pppoe.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """PPP-over-Ethernet.""" from __future__ import absolute_import import struct import codecs from . import dpkt from . import ppp from .decorators import deprecated # RFC 2516 codes PPPoE_PADI = 0x09 PPPoE_PADO = 0x07 PPPoE_PADR = 0x19 PPPoE_PADS = 0x65 PPPoE_PADT = 0xA7 PPPoE_SESSION = 0x00 class PPPoE(dpkt.Packet): """PPP-over-Ethernet. TODO: Longer class information.... Attributes: __hdr__: Header fields of PPPoE. TODO. """ __hdr__ = ( ('_v_type', 'B', 0x11), ('code', 'B', 0), ('session', 'H', 0), ('len', 'H', 0) # payload length ) @property def v(self): return self._v_type >> 4 @v.setter def v(self, v): self._v_type = (v << 4) | (self._v_type & 0xf) @property def type(self): return self._v_type & 0xf @type.setter def type(self, t): self._v_type = (self._v_type & 0xf0) | t def unpack(self, buf): dpkt.Packet.unpack(self, buf) try: if self.code == 0: # We need to use the pppoe.PPP header here, because PPPoE # doesn't do the normal encapsulation. self.data = self.ppp = PPP(self.data) except dpkt.UnpackError: pass class PPP(ppp.PPP): # Light version for protocols without the usual encapsulation, for PPPoE __hdr__ = ( # Usuaully two-bytes, but while protocol compression is not recommended, it is supported ('p', 'B', ppp.PPP_IP), ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) if self.p & ppp.PFC_BIT == 0: try: self.p = struct.unpack('>H', buf[:2])[0] except struct.error: raise dpkt.NeedData self.data = self.data[1:] try: self.data = self._protosw[self.p](self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) except (KeyError, struct.error, dpkt.UnpackError): pass def pack_hdr(self): try: # Protocol compression is *not* recommended (RFC2516), but we do it anyway if self.p > 0xff: return struct.pack('>H', self.p) return dpkt.Packet.pack_hdr(self) except struct.error as e: raise dpkt.PackError(str(e)) def test_pppoe_discovery(): s = ("11070000002801010000010300046413" "85180102000442524153010400103d0f" "0587062484f2df32b9ddfd77bd5b") s = codecs.decode(s, 'hex') p = PPPoE(s) assert p.code == PPPoE_PADO assert p.v == 1 assert p.type == 1 s = ("11190000002801010000010300046413" "85180102000442524153010400103d0f" "0587062484f2df32b9ddfd77bd5b") s = codecs.decode(s, 'hex') p = PPPoE(s) assert p.code == PPPoE_PADR assert p.pack_hdr() == s[:6] def test_pppoe_session(): s = "11000011000cc0210101000a050605fcd459" s = codecs.decode(s, 'hex') p = PPPoE(s) assert p.code == PPPoE_SESSION assert isinstance(p.ppp, PPP) assert p.data.p == 0xc021 # LCP assert len(p.data.data) == 10 assert p.data.pack_hdr() == b"\xc0\x21" s = ("110000110066005760000000003c3a40fc000000000000000000000000000001" "fc0000000002010000000000000100018100bf291f9700010102030405060708" "090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728" "292a2b2c2d2e2f3031323334") s = codecs.decode(s, 'hex') p = PPPoE(s) assert p.code == PPPoE_SESSION assert isinstance(p.ppp, PPP) assert p.data.p == ppp.PPP_IP6 assert p.data.data.p == 58 # ICMPv6 assert p.ppp.pack_hdr() == b"\x57" def test_ppp_packing(): p = PPP() assert p.pack_hdr() == b"\x21" p.p = 0xc021 # LCP assert p.pack_hdr() == b"\xc0\x21" def test_ppp_short(): import pytest pytest.raises(dpkt.NeedData, PPP, b"\x00") # XXX - TODO TLVs, etc.
{ "repo_name": "smutt/dpkt", "path": "dpkt/pppoe.py", "copies": "3", "size": "4030", "license": "bsd-3-clause", "hash": 6135819986621833000, "line_mean": 24.5063291139, "line_max": 96, "alpha_frac": 0.5816377171, "autogenerated": false, "ratio": 2.9181752353367125, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9999122967271392, "avg_score": 0.00013799703306378912, "num_lines": 158 }
# $Id: pppoe.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """PPP-over-Ethernet.""" import dpkt import ppp from decorators import deprecated # RFC 2516 codes PPPoE_PADI = 0x09 PPPoE_PADO = 0x07 PPPoE_PADR = 0x19 PPPoE_PADS = 0x65 PPPoE_PADT = 0xA7 PPPoE_SESSION = 0x00 class PPPoE(dpkt.Packet): __hdr__ = ( ('_v_type', 'B', 0x11), ('code', 'B', 0), ('session', 'H', 0), ('len', 'H', 0) # payload length ) @property def v(self): return self._v_type >> 4 @v.setter def v(self, v): self._v_type = (v << 4) | (self._v_type & 0xf) @property def type(self): return self._v_type & 0xf @type.setter def type(self, t): self._v_type = (self._v_type & 0xf0) | t # Deprecated methods, will be removed in the future # ================================================= @deprecated('v') def _get_v(self): return self.v @deprecated('v') def _set_v(self, v): self.v = v @deprecated('type') def _get_type(self): return self.type @deprecated('type') def _set_type(self, t): self.type = t # ================================================= def unpack(self, buf): dpkt.Packet.unpack(self, buf) try: if self.code == 0: self.data = self.ppp = ppp.PPP(self.data) except dpkt.UnpackError: pass # XXX - TODO TLVs, etc.
{ "repo_name": "yangbh/dpkt", "path": "dpkt/pppoe.py", "copies": "6", "size": "1440", "license": "bsd-3-clause", "hash": 7336883327411163000, "line_mean": 21.1538461538, "line_max": 57, "alpha_frac": 0.5020833333, "autogenerated": false, "ratio": 3.044397463002114, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 65 }
# $Id: ppp.py 65 2010-03-26 02:53:51Z dugsong $ # -*- coding: utf-8 -*- """Point-to-Point Protocol.""" import struct import dpkt # XXX - finish later # http://www.iana.org/assignments/ppp-numbers PPP_IP = 0x21 # Internet Protocol PPP_IP6 = 0x57 # Internet Protocol v6 # Protocol field compression PFC_BIT = 0x01 class PPP(dpkt.Packet): __hdr__ = ( ('p', 'B', PPP_IP), ) _protosw = {} @classmethod def set_p(cls, p, pktclass): cls._protosw[p] = pktclass @classmethod def get_p(cls, p): return cls._protosw[p] def unpack(self, buf): dpkt.Packet.unpack(self, buf) if self.p & PFC_BIT == 0: self.p = struct.unpack('>H', buf[:2])[0] self.data = self.data[1:] try: self.data = self._protosw[self.p](self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) except (KeyError, struct.error, dpkt.UnpackError): pass def pack_hdr(self): try: if self.p > 0xff: return struct.pack('>H', self.p) return dpkt.Packet.pack_hdr(self) except struct.error, e: raise dpkt.PackError(str(e)) def __load_protos(): g = globals() for k, v in g.iteritems(): if k.startswith('PPP_'): name = k[4:] modname = name.lower() try: mod = __import__(modname, g, level=1) PPP.set_p(v, getattr(mod, name)) except (ImportError, AttributeError): continue if not PPP._protosw: __load_protos()
{ "repo_name": "hexcap/dpkt", "path": "dpkt/ppp.py", "copies": "6", "size": "1621", "license": "bsd-3-clause", "hash": 2090922085786027500, "line_mean": 23.5606060606, "line_max": 74, "alpha_frac": 0.5305367057, "autogenerated": false, "ratio": 3.288032454361055, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6818569160061054, "avg_score": null, "num_lines": null }
# $Id: ppp.py 65 2010-03-26 02:53:51Z dugsong $ """Point-to-Point Protocol.""" import struct import dpkt # XXX - finish later # http://www.iana.org/assignments/ppp-numbers PPP_IP = 0x21 # Internet Protocol PPP_IP6 = 0x57 # Internet Protocol v6 # Protocol field compression PFC_BIT = 0x01 class PPP(dpkt.Packet): __hdr__ = ( ('p', 'B', PPP_IP), ) _protosw = {} def set_p(cls, p, pktclass): cls._protosw[p] = pktclass set_p = classmethod(set_p) def get_p(cls, p): return cls._protosw[p] get_p = classmethod(get_p) def unpack(self, buf): dpkt.Packet.unpack(self, buf) if self.p & PFC_BIT == 0: self.p = struct.unpack('>H', buf[:2])[0] self.data = self.data[1:] try: self.data = self._protosw[self.p](self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) except (KeyError, struct.error, dpkt.UnpackError): pass def pack_hdr(self): try: if self.p > 0xff: return struct.pack('>H', self.p) return dpkt.Packet.pack_hdr(self) except struct.error, e: raise dpkt.PackError(str(e)) def __load_protos(): g = globals() for k, v in g.iteritems(): if k.startswith('PPP_'): name = k[4:] modname = name.lower() try: mod = __import__(modname, g) except ImportError: continue PPP.set_p(v, getattr(mod, name)) if not PPP._protosw: __load_protos()
{ "repo_name": "wofanli/trex-core", "path": "scripts/external_libs/dpkt-1.8.6/dpkt/ppp.py", "copies": "15", "size": "1604", "license": "apache-2.0", "hash": 1289118461443130400, "line_mean": 24.4603174603, "line_max": 74, "alpha_frac": 0.5274314214, "autogenerated": false, "ratio": 3.2208835341365463, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" Every PSC and service has a profile used either declare the capabilities, requirements and restrictions of a component. Classes here deal with comparing profiles so as to simplify finding a match between, for example, services and PSCs. """ import re from fnmatch import fnmatchcase import os from types import StringType from peloton.exceptions import ConfigurationError from cStringIO import StringIO class BaseProfileComparator(object): """ Base class for all profile-comparing classes. In all methods, if optimistic is set True the test will be generous in the logic of the particular implementation. What is a profile? ================== A profile enables a component to advertise its properties to others. So a PSC will have a profile indicating, perhaps, what kind of host it is running on, how much memory is available to it and the maximum number of services it is permitted to manage. A service may have a profile describing its requirements, e.g. that it needs to run on a UN*X host with more than 8Gb of RAM, and that it needs to be run on a minimum of 4 PSCs across a minimum of 2 distinct hosts, for example. When a service is launched the service profile will be compared with PSC profiles to determine which host or combination of hosts might best be able to provide for this service. A profile may be built up from terms in a configuration file (in the [profile] section - all keys will be added to the profile) or at startup (so a PSC will put its details discovered at runtime into its own profile). Comparing profiles ================== It is not possible simply to ask if profile_A == profile_B or if profile_A > profile_B (implying some concept of 'exceeds the requirements' perhaps) with the simple algebraic comparison operators. We have instead to specify what keys get involved in the comparison and how to do that. For example, if a service has specified mincpus=2 we have to make clear that a PSC with cpus >= mincpus is OK. The dynamic requirements of this problem are made clear when it is considered that arbitrary entries in a profile may be meaningful in certain comparisons. For this reason comparisons are done with ProfileComparator classes of which a number of standard ones are provided and others may be written by developers. The comparison operators in the PelotonProfile are rendered un-useable. Where strings are being compared, if a value could logicaly be a pattern (e.g. hostname in a service profile) you can indicate whether it is a straight comparison, a regex or a fname pattern as follows: - r:<pattern> is a regular expression - f:<pattern> is a fnmatch pattern - s:<pattern> is a string. - <pattern> is also a string (the default) @todo: cast values for known keys as defined above """ def ge(self, x, y, optimistic=True): "Return true if x >= y in the logic of this comparator." raise NotImplementedError() def le(self, x, y, optimistic=True): "Return true if x <= y in the logic of this comparator." raise NotImplementedError() def eq(self, x, y, optimistic=True): "Return true if x == y in the logic of this comparator." raise NotImplementedError() def gt(self, x, y, optimistic=True): "Return true if x > y in the logic of this comparator." raise NotImplementedError() def lt(self, x, y, optimistic=True): "Return true if x < y in the logic of this comparator." raise NotImplementedError() class ServicePSCComparator(BaseProfileComparator): """ Compares a service profile with a PSC profile to determine if the PSC is suitable for running the service. In the logic of this class only equality is checked for; if svcProfile is determined equal to pscProfile it means that the PSC is adequate for the running of this service. This does not check properties such as the max number of services that a PSC is permitted to run as the comparison may be made on a node not privy to such information. Instead, the comparing node will request that a host node start a service and the host may choose at that point to reject the request. """ def eq(self, sp, pp, optimistic=True): """ Comparison based on checking the following keys (listed as key in service profile -- key in PSC profile): - hostname (pattern) -- hostname - [min|max]ram -- ram - [min|max]cpus -- cpus - platform (pattern) -- platform - flags -- flags - excludeFlags -- flags Flags are matched True if all the flags in the profile list are present in the service list and none of the flags in the excludeFlags list are present in the service profile. If send only the [profile] or [psclimits] section; keys must be in root of object provided. """ for service_key in sp.keys(): if service_key in ['minram', 'mincpus']: try: if self.__int_cf__(sp, service_key, pp, service_key[3:]) > 0: return False except: if not optimistic: return False elif service_key in ['maxram', 'maxcpus']: try: if self.__int_cf__(sp, service_key, pp, service_key[3:]) < 0: return False except: if not optimistic: return False elif service_key in ['hostname', 'platform']: if not self.__pattern_cf__(sp, service_key, pp, service_key): return False elif service_key == 'flags': flags = sp['flags'] pFlags = pp['flags'] for f in flags: if f not in pFlags: return False elif service_key == 'excludeFlags': flags = sp['excludeFlags'] pFlags = pp['flags'] for f in flags: if f in pFlags: return False return True def __int_cf__(self, profilea, keya, profileb, keyb): if profileb.has_key(keyb): va = int(profilea[keya]) vb = int(profileb[keyb]) return cmp(va, vb) else: raise ConfigurationError("No key in profile b") def __pattern_cf__(self, profilea, keya, profileb, keyb): pattern = profilea[keya] if not profileb.has_key(keyb): return False if pattern[:2] == 'r:': # this is a regex regex = re.compile(pattern[2:]) if regex.match(profileb[keyb]): return True else: return False elif pattern[:2] == 'f:': # fnmatch pattern pattern = pattern[2:] return fnmatchcase(profileb[keyb], pattern) else: # must be a string; remove initial s: if present if pattern[:2] == 's:': pattern = pattern[2:] return pattern == profileb[keyb] return False
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/profile.py", "copies": "1", "size": "7424", "license": "bsd-3-clause", "hash": -2195595440006133800, "line_mean": 37.2731958763, "line_max": 82, "alpha_frac": 0.6295797414, "autogenerated": false, "ratio": 4.382526564344746, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5512106305744746, "avg_score": null, "num_lines": null }
"""A self-filling widget for progress states.""" from BaseWidget import BaseWidget from Constants import * import base class ProgressBar (BaseWidget): """ProgressBar () -> ProgressBar A widget class, which can display a progress state. The Progressbar widget is a graphical state indicator, which can interactively show the effort of an operation by a filling bar. Its value ranges from 0 to 100 (percent) and can increase or decrease. To allow high interactivity, each value changing method of the ProgressBar will raise a SIG_VALCHANGED event. The increment of the ProgressBar can be set with the 'step' attribute or set_step() method. To allow a high resolution for long running tasks and operations, which should be visualized using the ProgressBar, the increment accepts floating point values. progressbar.step = 0.1 progressbar.set_step (10) The 'value' attribte and set_value() method allow setting the ProgressBar value directly without calling the respective increment or decerement methods. progressbar.value = 50.0 progressbar.set_value (3) The ProgressBar value can be in- or decreased using the increase() and decrease() methods. Those will in- or decrease the current value by the value of the 'step' attribute until either 100 or 0 is reached. progressbar.increase() progressbar.decrease() Dependant on the width of the ProgressBar the filled range per in- or decreasement can differ. The complete width is always used as the maximum value of 100, thus longer progressBar widgets allow better visible changes, if a finer grained increment is given. The ProgressBar uses a default size for itself by setting the 'size' attribute to a width of 104 pixels and a height of 24 pixels. Default action (invoked by activate()): None Mnemonic action (invoked by activate_mnemonic()): None Signals: SIG_VALCHANGED - Invoked, when the value of the ProgressBar changed. Attributes: step - Step range. value - Current value. text - The text to display on the ProgressBar. """ def __init__ (self): BaseWidget.__init__ (self) # The current value, max is 100 (%), min is 0 (%) and step range. self._value = 0 self._step = 0.1 self._text = None self._signals[SIG_VALCHANGED] = [] self.minsize = 104, 24 # Use a fixed size. def set_focus (self, focus=True): """P.set_focus (focus=True) -> None Overrides the set_focus() behaviour for the ProgressBar. The ProgressBar class is not focusable by default. It is an information displaying class only, so it does not need to get the input focus and thus it will return false without doing anything. """ return False def set_text (self, text): """P.set_text (...) -> None Sets the text to display on the ProgressBar. Sets the text text to display on the ProgressBar. The text will be centered on it. Raises a TypeError, if the passed argument is not a string or unicode. """ if type (text) not in (str, unicode): raise TypeError ("text must be a string or unicode") self._text = text self.dirty = True def set_step (self, step=0.1): """P.set_step (...) -> None Sets the step range for in- or decreasing the ProgressBar value. The step range is the value used by the increase and decrease methods of the ProgressBar. Raises a TypeError, if the passed argument is not a float or integer. """ if type (step) not in (float, int): raise TypeError ("step must be a float or integer") self._step = step def set_value (self, value): """P.set_value (...) -> None Sets the current value of the ProgressBar. Sets the current value of the ProgressBar and raises a SIG_VALCHANGED event, if the new value differs from the old one. Raises a TypeError, if the passed argument is not a float or integer. Raises a ValueError, if the passed argument, is not within the allowed range of 0.0 to 100.0. """ if type (value) not in (float, int): raise TypeError ("value must be a float or integer") if (0.0 > value) or (100.0 < value): raise ValueError ("value must be in the range from 0.0 to 100.0") if value != self._value: self._value = value self.run_signal_handlers (SIG_VALCHANGED) self.dirty = True def increase (self): """P.increase () -> None Increases the current value by one step. """ val = self.value if val < 100.0: val += self.step if val > 100.0: val = 100.0 self.value = val def decrease (self): """P.decrease () -> None Decreases the current value by one step. """ val = self.value if val > 0.0: val -= self.step if val < 0.0: val = 0.0 self.value = val def draw_bg (self): """P.draw_bg () -> Surface Draws the ProgressBar background surface and returns it. Creates the visible surface of the ProgressBar and returns it to the caller. """ return base.GlobalStyle.engine.draw_progressbar (self) def draw (self): """P.draw () -> None Draws the ProgressBar surface and places its text on it. """ BaseWidget.draw (self) if self.text: sf_text = base.GlobalStyle.engine.draw_string (self.text, self.state, self.__class__, self.style) rect = sf_text.get_rect () rect.center = self.image.get_rect ().center self.image.blit (sf_text, rect) value = property (lambda self: self._value, lambda self, var: self.set_value (var), doc = "The current value.") step = property (lambda self: self._step, lambda self, var: self.set_step (var), doc = "The step range of the ProgressBar.") text = property (lambda self: self._text, lambda self, var: self.set_text (var), doc = "The text to display on the ProgressBar.")
{ "repo_name": "prim/ocempgui", "path": "ocempgui/widgets/ProgressBar.py", "copies": "1", "size": "8098", "license": "bsd-2-clause", "hash": 7451137792997620000, "line_mean": 35.6425339367, "line_max": 78, "alpha_frac": 0.6254630773, "autogenerated": false, "ratio": 4.408274360370169, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5533737437670169, "avg_score": null, "num_lines": null }
""" Platform dependent implementations of some processes. For now, makeDaemon.""" import os def POSIX_makeDaemon(): """ Detach from the console, redirect stdin/out/err to/from /dev/null.""" # File mode creation mask of the daemon. UMASK = 0 # Default maximum for the number of available file descriptors. MAXFD = 1024 # The standard I/O file descriptors are redirected to /dev/null by default. if (hasattr(os, "devnull")): REDIRECT_TO = os.devnull else: REDIRECT_TO = "/dev/null" try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The first child. os.setsid() try: pid = os.fork() # Fork a second child. except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The second child. os.umask(UMASK) else: # exit() or _exit() - See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 os._exit(0) # Exit parent of the second child - the first child. else: os._exit(0) # Exit parent of the first child. # redirect stdin/out/err to /dev/null (or equivalent) fd = os.open(REDIRECT_TO, os.O_RDWR) # Duplicate fd to standard input, standard output and standard error. os.dup2(fd, 0) # standard input (0) os.dup2(fd, 1) # standard output (1) os.dup2(fd, 2) # standard error (2) def WINDOWS_makeDaemon(): print("Cannot daemonize on windows as yet. Start as a service or with 'start'") # Set makeDaemon according to platform if os.name in ['posix', 'mac']: makeDaemon = POSIX_makeDaemon else: makeDaemon = WINDOWS_makeDaemon
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/psc_platform.py", "copies": "1", "size": "1970", "license": "bsd-3-clause", "hash": -4631176222497227000, "line_mean": 31.2950819672, "line_max": 101, "alpha_frac": 0.6096446701, "autogenerated": false, "ratio": 3.5368043087971275, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9599736085401835, "avg_score": 0.00934257869905844, "num_lines": 61 }
from twisted.spread import pb from twisted.internet import reactor from twisted.internet.error import ConnectionRefusedError from twisted.internet.error import ConnectionDone from twisted.internet.defer import Deferred from peloton.exceptions import PelotonConnectionError from peloton.exceptions import PelotonError from peloton.exceptions import DeadProxyError from peloton.exceptions import NoWorkersError from types import StringType class PSCProxy(object): """ Base class for PSC proxies through which the routing table can exchange messages with PSCs. A proxy is required because the PSC may be the local process, a PSC in the domain or a PSC in another domain on the grid. """ def __init__(self, kernel, profile): self.profile = profile self.kernel = kernel self.logger = kernel.logger self.ACCEPTING_REQUESTS = True self.RUNNING = True def call(self, service, method, *args, **kwargs): """ Request the serice method be called on this PSC. """ raise NotImplementedError def stop(self): """ May be implemented if some action on stop is required. """ self.RUNNING = False def getInterface(self, name): """ Returns the named plugin interface. """ raise NotImplementedError class LocalPSCProxy(PSCProxy): """ Proxy for this 'local' PSC. """ def call(self, service, method, *args, **kwargs): """ Use the following process to call the method: - obtain a worker reference - call the method in there - park the deferred; return a new deferred to the caller of this method - if error, reset and try again. - if no error, put result onto return deferred. The coreio call method will receive a deferred OR a NoWorkersError will be raised. """ rd = Deferred() rd._peloton_loopcount = 0 # used in _call self._call(rd, service, method, args, kwargs) return rd def _call(self, rd, service, method, args, kwargs): while True: try: # p = self.kernel.workerStore[service].getRandomWorker() p = self.kernel.workerStore[service].getNextWorker() d = p.callRemote('call',method, *args, **kwargs) d.addCallback(rd.callback) d.addErrback(self.__callError, rd, p, service, method, args, kwargs) break except pb.DeadReferenceError: self.logger.error("Dead reference for %s worker" % service) self.kernel.workerStore[service].notifyDeadWorker(p) except NoWorkersError: # Clearly we expect to be able to provide this service # otherwise we'd not be here so it is quite likely that # for some reason all the workers got zapped and more are # in the process of starting. We'll try periodicaly to see # if this is true but after 3 seconds timeout and give up # for good. if rd._peloton_loopcount >= 300: rd.errback(NoWorkersError("No workers for service %s" % service)) else: rd._peloton_loopcount+=1 reactor.callLater(0.01, self._call, rd, service, method, args, kwargs) break def __callError(self, err, rd, p, service, method, args, kwargs): """ A twisted error occured when making the remote call. This is going to be one of: - An application error raised in the service - this must pass through. It will be characterised by err.value being a string - A connection was broken whilst the call was being made; flag the worker as dead and start again. This is signified by err.value being a pb.PBConnectionLost error. - The connection was closed cleanly whilst performing the operation; likely the service was re-started. Current protocol is to re-issue the request but in future the old worker may well finish the job so this error will not be raised. This condition is signified by err.value being a ConnectionDone instance. """ if isinstance(err.value, pb.PBConnectionLost) or \ isinstance(err.value, ConnectionDone): if self.RUNNING: self.kernel.workerStore[service].notifyDeadWorker(p) self._call(rd, service, method, args, kwargs) else: rd.errback(NoWorkersError("No workers for service %s" % service)) else: rd.errback(err) class TwistedPSCProxy(PSCProxy): """ Proxy for a PSC that is running on the same domain as this node and accepts Twisted PB RPC. This is the prefered proxy to use if a node supports it and if it is suitably located (i.e. same domain).""" def __init__(self, kernel, profile): PSCProxy.__init__(self, kernel, profile) self.peer = None self.remoteRef = None self.CONNECTING = False self.ACCEPTING_REQUESTS = True self.requestCache = [] # deferreds that need calling back when the connection # is made self.startupListeners = [] def call(self, service, method, *args, **kwargs): if not self.ACCEPTING_REQUESTS: raise DeadProxyError("Cannot accept requests.") d = Deferred() if self.remoteRef == None: self.requestCache.append([d, service, method, args, kwargs]) sud = Deferred() sud.addCallback(self.flushRequests) sud.addErrback(self.flushRequestsErr) self.startupListeners.append(sud) if not self.CONNECTING: self.__connect() else: try: self.__call(d, service, method, args, kwargs) except pb.DeadReferenceError: self.ACCEPTING_REQUESTS = False raise DeadProxyError("Dead reference to remote PSC") return d def __call(self, d, service, method, args, kwargs): cd = self.remoteRef.callRemote('relayCall', service, method, *args, **kwargs) cd.addCallback(d.callback) cd.addErrback(self.__callError, d, service, method) def __callError(self, err, d, service, method): # self.logger.error("** Call error calling %s.%s: %s" % (service, method, err.parents[-1])) if err.parents[-1] == 'twisted.spread.pb.PBConnectionDone' or \ err.parents[-1] == 'twisted.spread.pb.PBConnectionLost': # self.logger.error("CALL ERROR %s CALLING %s.%s" % (err.parents[-1], service, method)) d.errback(DeadProxyError("Peer closed connection")) else: d.errback(err) def getInterface(self, name): d = Deferred() if self.remoteRef == None: sud = Deferred() self.startupListeners.append(sud) sud.addCallback(self._getInterface,d, name) sud.addErrback(self._getInterfaceErr, d) if not self.CONNECTING: self.__connect() else: self._getInterface(0, d, name) return d def _getInterface(self, _, d, name): dd = self.remoteRef.callRemote("getInterface", name) dd.addCallback(d.callback) dd.addErrback(d.errback) def _getInterfaceErr(self, err, d): d.errback(DeadProxyError("Could not obtain interface from remote PSC")) def __connect(self): """ Connections to peers are made on demand so that only links that are actively used get made. This is the start of the connect sequence.""" self.CONNECTING = True # self.logger.debug("CONNECT TO REMOTE PSC") factory = pb.PBClientFactory() reactor.connectTCP(self.profile['ipaddress'], self.profile['port'], factory) cd = factory.getRootObject() cd.addCallback(self.__peerConnect) cd.addErrback(self.__connectError, "Error connecting to peer") def __peerConnect(self, peer): self.peer = peer pd = peer.callRemote('registerPSC', self.kernel.guid) pd.addCallback(self.__refReceived) pd.addErrback(self.__connectError, "Error receiving remote reference") def __refReceived(self, ref): self.remoteRef = ref self.CONNECTING = False while self.startupListeners: self.startupListeners.pop().callback(True) def __connectError(self, err, msg): self.ACCEPTING_REQUESTS = False self.CONNECTING = False self.logger.error("TwistedPSCProxy: %s" % msg) while self.startupListeners: self.startupListeners.pop().errback(err) def flushRequests(self, _): self.logger.debug("Flushing %d requests" % len(self.requestCache)) while self.requestCache: req = self.requestCache.pop(0) d = req[0] request = req[1:] self.__call(d, *request) def flushRequestsErr(self, err): """ Called if there was a failure connecting to PSC. """ while self.requestCache: req = self.requestCache.pop(0) d = req[0] d.errback(DeadProxyError("Peer not present before connect (%s)" % err.getErrorMessage())) def stop(self): if self.RUNNING: self.ACCEPTING_REQUESTS = False PSCProxy.stop(self) self.peer = self.remoteRef = None class MessageBusPSCProxy(PSCProxy): """ Proxy for a PSC that is able only to accept RPC calls over the message bus for whatever reason. """ pass # mapping of proxy to specific RPC mechanisms # that a PSC may accept PSC_PROXIES = {'pb' : TwistedPSCProxy, 'bus' : MessageBusPSCProxy}
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/pscproxies.py", "copies": "1", "size": "10097", "license": "bsd-3-clause", "hash": -5892515390481571000, "line_mean": 39.0714285714, "line_max": 101, "alpha_frac": 0.6135485788, "autogenerated": false, "ratio": 4.174038859032658, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5287587437832657, "avg_score": null, "num_lines": null }
""" PSC: Peloton Service Controller The service controller is the primary unit in the Peloton mesh. PSC units link together to form a mesh; each PSC manages a number of services. How those services are managed is dependent on the controller; some may be developed to work in different ways. The default behaviour for this core PSC will be to spawn a worker process to run a service, each worker then running a certain number of threads. This allows us to tune the process vs thread ratio to the strengths of different platforms. A PSC will communicate with other PSCs via Twisted RPC, via RPC over message bus or by other protocols to be defined in future. The acceptable protocols are listed in the PSC signature. This script is pretty shallow: it simply starts the kernel using some platform-specific code where required after first processing out command line arguments. """ # Random is used in many places in Peloton, so get it seeded # right away. import random random.seed() ######################## import peloton import peloton.utils.logging as logging import os import sys from peloton.utils.structs import FilteredOptionParser from peloton.psc_platform import makeDaemon from peloton.kernel import PelotonKernel from peloton.utils.config import PelotonSettings from peloton.utils import deCompound def start(pc): """ Start a PSC. By default the first step is to daemonise, either by a double fork (on a POSIX system) or by re-spawning the process (on Windows) to detach from the console; this can be over-ridden by specifying --nodetach on the command line. The kernel is then started. This creates worker processes as required via the subprocess module. """ if not pc.nodetach: makeDaemon() logging.initLogging(rootLoggerName='PSC', logLevel=getattr(logging, pc.loglevel), logdir=pc.logdir, logfile='psc.log', logToConsole=pc.nodetach) logging.getLogger().info("Kernel starting; pid = %d" % os.getpid()) kernel = PelotonKernel(pc) logging.setAdditionalLoggers(kernel) ex = kernel.start() return ex def main(): # Let's read the command line usage = "usage: %prog [options]" # add 'arg1 arg2' etc as required parser = FilteredOptionParser(usage=usage, version="Peloton version %s" % peloton.RELEASE_VERSION) # parser.set_defaults(nodetach=False) parser.add_option("--prefix", help="Prefix directory to help with setting paths") parser.add_option("--nodetach", action="store_true", default=False, help="Prevent PSC detaching from terminal [default: %default]") parser.add_option("-c", "--configfile", help="Path to configuration file for the PSC [default: %default].", dest="configfile", default='psc.pcfg') parser.add_option("-b", "--bind", help="""specify the host:port to which this instance should bind. Overides values set in configuration.""", dest='bindhost') parser.add_option("--anyport", action="store_true", default=False, help="""When set, this permits the PSC to seek a free port if the configured port is not available.""") parser.add_option("-s", "--servicepath", help="""Directory containing peloton services. You may specify several such directories with multiple instances of this option [default: %default]""", action="append", default=["$PREFIX/service"]) parser.add_option("--loglevel", help="""Set the logging level to one of critical, fatal, error(uat, prod), warning, info(test), debug(dev). (defaults for each run mode indicated in brackets).""", choices=['critical', 'fatal', 'error', 'warning', 'info', 'debug']) parser.add_option("--logdir", help="""Directory to which log files should be written. By setting this argument the logging-to-file system will be enabled.""") parser.add_option("--disable", help="""Comma delimited list of plugins to prevent starting even if configuration has them enabled""", action="append") parser.add_option("--enable", help="""Comma delimited list of plugins to start even if configuration has them disabled""", action="append") parser.add_option("--flags", help="""Comma delimited list of flags to add to this PSC.""", action="append") options, args = parser.parse_args() # Handling errors and pumping back through the system #if len(args) != 1: # parser.error("incorrect number of arguments") # add any sevice directories to sys.path if not already there for sd in options.servicepath: if sd not in sys.path: sys.path.append(sd) # enable, disable and flags are all 'append' types, but allow # comma delimited entries as well so we need to turn the list of # n potentially compound entries into a single list if options.enable: options.enable = deCompound(options.enable) else: options.enable=[] if options.disable: options.disable = deCompound(options.disable) else: options.disable=[] if options.flags: options.flags = deCompound(options.flags) else: options.flags=[] # determine the appropriate log-level for the root logger based # on supplied arguments. if options.loglevel: options.loglevel = options.loglevel.upper() else: options.loglevel = "ERROR" # Load configuration from file pc = PelotonSettings() try: pc.load(options.configfile) except IOError: sys.stderr.write("There is no profile for the PSC!\n") return 1 if pc.profile.has_key('flags'): pc.profile.flags.extend(options.flags) else: pc.profile.flags = options.flags # copy in the necessary from options to config keys =['configfile', 'nodetach', 'bindhost', 'anyport', 'servicepath', 'loglevel', 'logdir', 'enable', 'disable'] for k in keys: pc[k] = getattr(options, k) try: exitCode = start(pc) except: logging.getLogger().exception('Untrapped error in PSC: ') exitCode = 99 return exitCode if __name__ == '__main__': # returns 1 if no profile can be read # returns 99 for untrapped error sys.exit(main())
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/psc.py", "copies": "1", "size": "6998", "license": "bsd-3-clause", "hash": 8918095472367793000, "line_mean": 34.8871794872, "line_max": 129, "alpha_frac": 0.6284652758, "autogenerated": false, "ratio": 4.349285270354257, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5477750546154257, "avg_score": null, "num_lines": null }
""" Core code for Peloton TAP utilities (event viewers). This same code can be hooked into GUIs or console tools via handler hooks. """ from twisted.internet import reactor from twisted.spread import pb from peloton.utils.config import PelotonSettings class EventHandler(pb.Referenceable): def __init__(self, callback): self.callback = callback def remote_eventReceived(self, msg, exchange, key, ctag): self.callback(msg, exchange, key, ctag) class ClosedownListener(pb.Referenceable): def __init__(self, tapConnector, callback): self.tapConnector = tapConnector self.callback = callback def remote_eventReceived(self,msg, exchange, key, ctag): if msg['action'] == 'disconnect' and \ msg['sender_guid'] == self.tapConnector.pscProfile['guid']: self.callback() class TAPConnector(object): """ State object which hooks into a PSC and relays events back to the client. Manages re-connecting on disconnect also. A user of this class can hook into particular events, providing a callback method to be fired at appropriate times. The events are: - loggedin - profileReceived - exchangesReceived """ def __init__(self, host, port, username='tap', password='tap'): """ self-explanatory arguments. """ self.host = host self.port = port self.username = username self.password = password self.CONNECTED = False self.callbackNames = ['loggedin', 'disconnected', 'masterProfileReceived', 'profileReceived', 'exchangesReceived'] self.listeners = {} for cb in self.callbackNames: self.listeners[cb] = [] def start(self): self.connect() reactor.run() ## CALLBACK MANAGEMENT def addListener(self, callback, handler): if callback not in self.callbackNames: raise Exception("Invalid callback %s: must be one of %s" \ % (callback, str(self.callbackNames))) self.listeners[callback].append(handler) def removeListener(self, callback, handler): if handler in self.listeners[callback]: self.listeners[callback].remove(handler) def fireCallback(self, callback, *args): for cb in self.listeners[callback]: cb(*args) # END CALLBACK MANAGEMENT def addEventHandler(self, key, exchange, handler): handler = EventHandler(handler) self.iface.callRemote("register", key, handler, exchange) return handler def removeEventHandler(self, handler): self.iface.callRemote("deregister", handler) def getPSCProfile(self, guid=None): d = self.iface.callRemote('getPSCProfile', guid) if guid==None: upstream=True else: upstream=False d.addCallback(self.__profileReceived, upstream) d.addErrback(self.__callError, False) def connect(self): """ Initialise the connection sequence. Reactor must be started already, or started afterwards. """ factory = pb.PBClientFactory() reactor.connectTCP(self.host, self.port, factory) d = factory.getRootObject() d.addCallback(self.__connected) d.addErrback(self.__connectionError) def stop(self): reactor.stop() def __connected(self, ro): self.rootObject = ro self.CONNECTED = True d = self.rootObject.callRemote('login', self.username) d.addCallback(self.__receivedIface) d.addErrback(self.__connectionError) def __receivedIface(self, iface): self.iface = iface self.fireCallback('loggedin') self.getPSCProfile() d = self.iface.callRemote('getRegisteredExchanges') d.addCallback(self.__exchangesReceived) d.addErrback(self.__callError) self.closedownHandler = ClosedownListener(self, self.__pscClosedown) self.iface.callRemote('register', 'psc.presence', \ self.closedownHandler, 'domain_control') def __profileReceived(self, profile, upstreamPSC=False): profile = eval(profile) if upstreamPSC: self.pscProfile = profile self.fireCallback('masterProfileReceived', profile) self.fireCallback("profileReceived", profile) def __exchangesReceived(self, exchanges): self.exchanges = exchanges self.fireCallback("exchangesReceived", exchanges) def __pscClosedown(self): self.CONNECTED = False self.fireCallback("disconnected") reactor.callLater(1, self.connect) def __connectionError(self, err): self.CONNECTED = False self.fireCallback("disconnected") reactor.callLater(1, self.connect) def __callError(self, err, display=True): if display: print("Error making call: %s " % str(err))
{ "repo_name": "aquamatt/Peloton", "path": "src/tools/ptap/tapcore.py", "copies": "1", "size": "5294", "license": "bsd-3-clause", "hash": 974978182210717300, "line_mean": 34.0662251656, "line_max": 76, "alpha_frac": 0.6195693238, "autogenerated": false, "ratio": 4.307567127746135, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.025866331949130725, "num_lines": 151 }
""" This plugin module is ONLY for testing and first-stop try-before-you-buy. As an MQ provider it does little to ensure stability, capacity, persistence... in fact it does almost nothing x that AMQP does, it is simply a call-alike module that allows shallow testing. """ from peloton.plugins import PelotonPlugin from peloton.events import AbstractEventBusPlugin from peloton.events import AbstractEventHandler from peloton.exceptions import ConfigurationError from peloton.exceptions import PluginError from twisted.internet import reactor from twisted.internet.error import CannotListenError from twisted.spread import pb import cPickle as pickle class PseudoMQ(PelotonPlugin, AbstractEventBusPlugin): """ This plugin provides a fake AMQP provider with almost no facilities of a real provider! Essentially any exchange can be made and they're all topic exchanges. Everything is held in RAM; there's no guarantee of anything. It's for testing. Read again: It's for testing. One node must be started as a server (flag 'mqserver' is set) and all others must be clients (flag 'mqserver' is not set). The system is run entirely over PB and cannot be used to simulate messaging between domains. This can only run a single domain. If it is a server it creates the PseudoMQServer pb.Root object and publishes on the port specified in config. If it is a client it creates a PseudoMQClient referenceable, connects to the server and gets the root object. Code can register, de-register and fire events on the plugin as required by the AbstractEventBusPlugin. There's no guarantee that this is particularly neat - after a while you may find memory structures getting large even though you've been de-registering handlers. When registering, if a client, local exchanges/queues are formed with the local handler as a recipient. In addition registration is made on the server with the PseudoMQClient provided as a handler. When an event is fired on the server it is sent to all its local listeners and all the remote handlers. The remote clients then pass that to the plugin eventReceived which fires it on to all its local handlers. If a client, a fire event fires the event on the server directly then the above process takes place. The PseudoExchange and PseudoQueue classes model exchanges and queues and just simplify the event firing procedure. PseudoExchange has to determine which queues to pass the event to based on the event key and the queue keys. It has to match based on AMQP pattern matching rules; this is done with the matchKey method. """ def initialise(self): self.isServer = self.kernel.hasFlag('mqserver') self.host, port = self.config.host.split(':') try: self.port = int(port) except ValueError: raise ConfigurationError("Cannot connect pseudomq to port: %s" % port) self.exchanges={} # initialise with the three key exchanges for x in ['domain_control', 'events', 'logging']: self.exchanges[x] = PseudoExchange(x) def start(self): if self.isServer: self.connection = None self._startServer() else: self.connected = False self.server=None self._startClient() self.registrationQueue = [] self.eventFiringQueue = [] def stop(self): if self.isServer and self.connection: self.connection.stopListening() elif self.server: # must find out how to disconnet a client pass def register(self, key, handler, exchange='events'): # self.logger.debug("Registration called on %s.%s" % (exchange, key)) try: self.exchanges[exchange].addQueue(key, handler) except KeyError: self.exchanges[exchange] = PseudoExchange(exchange) self.exchanges[exchange].addQueue(key, handler) if not self.isServer: if self.connected: self.server.callRemote('register', key, self.clientObj, exchange) else: self.registrationQueue.append((key, exchange)) def deregister(self, handler): for exchange in self.exchanges.values(): exchange.deregister(handler) def fireEvent(self, key, exchange='events', **kwargs): """ If I'm the server I fire to all my handlers, many of which will be remote. If I'm a client I call fireEvent on the server. """ # self.logger.debug("Fire event on %s.%s" % (exchange, key)) if 'sender_guid' not in kwargs.keys(): kwargs.update({'sender_guid' : self.kernel.guid}) if self.isServer: try: exchange = self.exchanges[exchange] exchange.fireEvent(key, kwargs) except KeyError: # no registration for this exchange. hey ho. pass else: if self.connected: try: self.server.callRemote('fireEvent', key, exchange, pickle.dumps(kwargs)) except pb.DeadReferenceError: self.connected=False self.logger.error("Message server has gone!") self.eventFiringQueue.append((key, exchange, kwargs)) else: self.eventFiringQueue.append((key, exchange, kwargs)) def getRegisteredExchanges(self): return self.exchanges.keys() def eventReceived(self, msg, exchange, key, ctag=''): """ Forward event received from server to locally registered nodes. """ msg = pickle.loads(msg) try: exchange = self.exchanges[exchange] exchange.fireEvent(key, msg) except KeyError: # no registration for this exchange. hey ho. pass def _startServer(self): """ Connect a server PB interface to whatever port is specified in the config. """ rootObj = PseudoMQServer(self) svr = pb.PBServerFactory(rootObj) try: self.connection = reactor.listenTCP(self.port, svr, interface=self.host) except CannotListenError: raise PluginError("PseudoMQ cannot bind to %s:%s" % (self.host, self.port)) except Exception: self.logger.exception("Error initialising PseudoMQ") def _startClient(self): """ Get a connection to a PseudoMQ server node. """ self.clientObj = PseudoMQClient(self) factory = pb.PBClientFactory() try: reactor.connectTCP(self.host, self.port, factory) d = factory.getRootObject() d.addCallback(self._clientConnect) d.addErrback(self._clientConnectError) except Exception, ex: raise PluginError("Could not connect to PseudoMQ server: %s" % str(ex)) def _clientConnect(self, svr): """ Called when root object from PseudoMQ server obtained. """ self.server = svr self._safeQueuePurge() def _safeQueuePurge(self, *args): """ Registrations made prior to the server being connected are flushed out one at a time (to preserve order). Then, events remaining to be fired are flushed out one at a time. Then we consider ourselves connected. """ if self.registrationQueue: key,exchange = self.registrationQueue.pop() d = self.server.callRemote('register', key, self.clientObj, exchange) d.addCallback(self._safeQueuePurge) elif self.eventFiringQueue: key, exchange, msg = self.eventFiringQueue.pop() d = self.server.callRemote('fireEvent', key, exchange, pickle.dumps(msg)) d.addCallback(self._safeQueuePurge) else: self.connected = True def _clientConnectError(self, err): """ Error connecting the client to the server """ raise PluginError("Could not connect to PseudoMQ server: %s" % str(err)) class PseudoMQServer(pb.Root): def __init__(self, pseudomq): self.pseudomq = pseudomq def remote_register(self, key, handler, exchange='events'): self.pseudomq.register(key, handler, exchange) def remote_deregister(self, handler): self.pseudomq.deregister(handler) def remote_fireEvent(self, key, exchange='events', msg=''): kwargs = pickle.loads(msg) self.pseudomq.fireEvent(key, exchange, **kwargs) class PseudoMQClient(pb.Referenceable): def __init__(self, pseudomq): self.pseudomq = pseudomq def remote_eventReceived(self, msg, exchange='', key='', ctag=''): self.pseudomq.eventReceived(msg, exchange, key, ctag) class PseudoExchange(object): """ Model an exchange in a super simplistic way. Allow registration of listeners to queues and firing of events. """ def __init__(self, name): self.name = name self.queues = {} def addQueue(self, key, handler): try: self.queues[key].addHandler(handler) except KeyError: self.queues[key] = PseudoQueue(key) self.queues[key].addHandler(handler) def deregister(self, handler): """ De-register handler from all queues to which it is registered. """ for queue in self.queues.values(): queue.removeHandler(handler) def fireEvent(self, key, msg): """ Fire event to all queues whose routing key matches the message key according to AMQP pattern matching rules. """ keys = self.queues.keys() matchKeys = [k for k in keys if self.matchKey(k, key)] for k in matchKeys: self.queues[k].fireEvent(key, self.name, msg) def matchKey(self, pattern, key): """ Pattern is a topic routing key pattern as defined by the AMQP specification. Return True if key matches the pattern, False otherwise. A pattern is a string of '.' delimited tokens. Permitted wildcards are: - # : matches zero or more tokens - * : matches a single token """ patternTokens = pattern.split('.') keyTokens = key.split('.') return self._matchKey(patternTokens, keyTokens) def _matchKey(self, pt, kt): """ Recursive matching method. """ if pt==[] and kt==[]: return True elif pt==[]: # there's no more pattern but there remain keytokens # un-matched. return False if pt[0] == '#': # peek at next pattern value and scroll forward in # key tokens until found if len(pt) > 1: peek = pt[1] else: # we're at the last element in pattern and it's a # hash so whatever is remaining in the key tokens, # it's OK - we have a match return True # find the first match of the next token in key space, # then match on the rest of the key tokens. If no match, # seek another match on the peeked token (this allows for # a.#.b.c to match a.x.x.b.x.x.b.c startPos = 0 while True: try: targetPos = kt[startPos:].index(peek) match = self._matchKey(pt[1:], kt[startPos+targetPos:]) if match: return True elif startPos+targetPos+1 == len(kt): # no more places to try match return False else: startPos += targetPos+1 except ValueError: # the key tokens do not contain the next token # in the pattern return False elif pt[0] == '*': if not kt: return False else: return self._matchKey(pt[1:], kt[1:]) elif (pt and kt) and (pt[0] == kt[0]): return self._matchKey(pt[1:], kt[1:]) else: return False class PseudoQueue(object): def __init__(self, key): self.key = key self.handlers = [] def addHandler(self, handler): if handler not in self.handlers: self.handlers.append(handler) def removeHandler(self, handler): try: self.handlers.remove(handler) except ValueError: # value not in list. Hey ho pass def fireEvent(self, key, exchange, message): msgPickle = pickle.dumps(message) deadHandlers = [] for h in self.handlers: if isinstance(h, AbstractEventHandler): try: h.eventReceived(message, exchange, key, '') except: deadHandlers.append(h) else: try: h.callRemote('eventReceived', msgPickle, exchange, key, '') except pb.DeadReferenceError: deadHandlers.append(h) for h in deadHandlers: self.handlers.remove(h)
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/plugins/pseudomq.py", "copies": "1", "size": "13652", "license": "bsd-3-clause", "hash": 8456619988366326000, "line_mean": 37.4591549296, "line_max": 92, "alpha_frac": 0.5987401113, "autogenerated": false, "ratio": 4.332592827673754, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5431332938973754, "avg_score": null, "num_lines": null }
""" The PWP (Peloton Worker Process) is spawned by the PSC to run a service worker. Originaly workers were spawned by forking but this has a couple of disadvantages: - It's not compatible with non-POSIX systems, notably a certain well known platform. - The forking seemed to leave the worker processes in a 'strange' state that may have caused problems with Twisted that were never resolved. """ import sys from peloton.worker import PelotonWorker from peloton.utils import chop def main(): """ Steps to start: 1. Obtain host, port from args 2. Obtain token from stdin 3. Call in and get service name, logdir (if any), launchTime etc 4. Startup """ host, port = sys.argv[1:3] port=int(port) token = chop(sys.stdin.readline()) worker = PelotonWorker(host, port, token) return worker.start() if __name__ == '__main__': sys.exit(main())
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/pwp.py", "copies": "1", "size": "1074", "license": "bsd-3-clause", "hash": 5126764069858576000, "line_mean": 28.027027027, "line_max": 68, "alpha_frac": 0.6918063315, "autogenerated": false, "ratio": 3.487012987012987, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46788193185129867, "avg_score": null, "num_lines": null }
"""$Id: pydbbdb.py,v 1.45 2008/05/31 11:49:01 rockyb Exp $ Routines here have to do with the subclassing of bdb. Defines Python debugger Basic Debugger (Bdb) class. This file could/should probably get merged into bdb.py """ import bdb, inspect, linecache, time, types from repr import Repr from fns import * ## from complete import rl_complete class Bdb(bdb.Bdb): # Additional levels call frames usually on the stack. # Perhaps should be an instance variable? extra_call_frames = 7 # Yes, it's really that many! def __init__(self): bdb.Bdb.__init__(self) self.bdb_set_trace = bdb.Bdb.set_trace ## self.complete = lambda arg: complete.rl_complete(self, arg) # Create a custom safe Repr instance and increase its maxstring. # The default of 30 truncates error messages too easily. self._repr = Repr() self._repr.maxstring = 100 self._repr.maxother = 60 self._repr.maxset = 10 self._repr.maxfrozen = 10 self._repr.array = 10 self._saferepr = self._repr.repr # A 0 value means stop on this occurrence. A positive value means to # skip that many more step/next's. self.step_ignore = 0 # Do we want to show/stop at def statements before they are run? self.deftrace = False return def __print_call_params(self, frame): "Show call paramaters and values" self.setup(frame) # Does sure format_stack_entry have an 'include_location' parameter? fse_code = self.format_stack_entry.func_code fse_args = fse_code.co_varnames if 'include_location' in fse_args: self.msg(self.format_stack_entry(self.stack[-1], include_location=False)) else: self.msg(self.format_stack_entry(self.stack[-1])) def __print_location_if_trace(self, frame, include_fntrace=True): if self.linetrace or (self.fntrace and include_fntrace): self.setup(frame) self.print_location(print_line=True) self.display.displayAny(self.curframe) if self.linetrace_delay: time.sleep(self.linetrace_delay) def bp_commands(self, frame): """Call every command that was set for the current active breakpoint (if there is one) Returns True if the normal interaction function must be called, False otherwise """ # self.currentbp is set in bdb.py in bdb.break_here if # a breakpoint was hit if getattr(self,"currentbp",False) and self.currentbp in self.commands: currentbp = self.currentbp self.currentbp = 0 lastcmd_back = self.lastcmd self.setup(frame, None) for line in self.commands[currentbp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[currentbp]: self.print_location(print_line=self.linetrace) if self.commands_doprompt[currentbp]: self.cmdloop() self.forget() return False return True def is_running(self): if self.running: return True self.errmsg('The program being debugged is not being run.') return False def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ if os.path.isabs(filename) and os.path.exists(filename): return filename f = os.path.join(sys.path[0], filename) if os.path.exists(f) and self.canonic(f) == self.mainpyfile: return f root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None # Override Bdb methods def bpprint(self, bp, out=None): if bp.temporary: disp = 'del ' else: disp = 'keep ' if bp.enabled: disp = disp + 'y ' else: disp = disp + 'n ' self.msg('%-4dbreakpoint %s at %s:%d' % (bp.number, disp, self.filename(bp.file), bp.line), out) if bp.cond: self.msg('\tstop only if %s' % (bp.cond)) if bp.ignore: self.msg('\tignore next %d hits' % (bp.ignore), out) if (bp.hits): if (bp.hits > 1): ss = 's' else: ss = '' self.msg('\tbreakpoint already hit %d time%s' % (bp.hits, ss), out) def output_break_commands(self): "Output a list of 'break' commands" # FIXME: for now we ae going to assume no breakpoints set # previously bp_no = 0 out = [] for bp in bdb.Breakpoint.bpbynumber: if bp: bp_no += 1 if bp.cond: condition = bp.cond else: condition = '' out.append("break %s:%s%s" % (self.filename(bp.file), bp.line, condition)) if not bp.enabled: out.append("disable %s" % bp_no) return out def break_here(self, frame): """This routine is almost copy of bdb.py's routine. Alas what pdb calls clear gdb calls delete and gdb's clear command is different. I tried saving/restoring method names, but that didn't catch all of the places break_here was called. """ filename = self.canonic(frame.f_code.co_filename) if not filename in self.breaks: return False lineno = frame.f_lineno if not lineno in self.breaks[filename]: # The line itself has no breakpoint, but maybe the line is the # first line of a function with breakpoint set by function name. lineno = frame.f_code.co_firstlineno if not lineno in self.breaks[filename]: return False # flag says ok to delete temp. bp (bp, flag) = bdb.effective(filename, lineno, frame) if bp: ## This is new when we have thread debugging. self.currentbp = bp.number if hasattr(bp, 'thread_name') and hasattr(self, 'thread_name') \ and bp.thread_name != self.thread_name: return False if (flag and bp.temporary): #### ARG. All for the below name change. self.do_delete(str(bp.number)) return True else: return False def canonic(self, filename): """ Overrides bdb canonic. We need to ensure the file we return exists! """ if filename == "<" + filename[1:-1] + ">": return filename canonic = self.fncache.get(filename) if not canonic: lead_dir = filename.split(os.sep)[0] if lead_dir == os.curdir or lead_dir == os.pardir: # We may have invoked the program from a directory # other than where the program resides. filename is # relative to where the program resides. So make sure # to use that. canonic = os.path.abspath(os.path.join(self.main_dirname, filename)) else: canonic = os.path.abspath(filename) if not os.path.isfile(canonic): canonic = search_file(filename, self.search_path, self.main_dirname) # Not if this is right for utter failure. if not canonic: canonic = filename canonic = os.path.normcase(canonic) self.fncache[filename] = canonic return canonic def canonic_filename(self, frame): return self.canonic(frame.f_code.co_filename) def clear_break(self, filename, lineno): filename = self.canonic(filename) if not filename in self.breaks: self.errmsg('No breakpoint at %s:%d.' % (self.filename(filename), lineno)) return [] if lineno not in self.breaks[filename]: self.errmsg('No breakpoint at %s:%d.' % (self.filename(filename), lineno)) return [] # If there's only one bp in the list for that file,line # pair, then remove the breaks entry brkpts = [] for bp in bdb.Breakpoint.bplist[filename, lineno][:]: brkpts.append(bp.number) bp.deleteMe() if not bdb.Breakpoint.bplist.has_key((filename, lineno)): self.breaks[filename].remove(lineno) if not self.breaks[filename]: del self.breaks[filename] return brkpts def complete(self, text, state): "A readline complete replacement" if hasattr(self, "completer"): if self.readline: line_buffer = self.readline.get_line_buffer() cmds = self.all_completions(line_buffer, False) else: line_buffer = '' cmds = self.all_completions(text, False) self.completer.namespace = dict(zip(cmds, cmds)) args=line_buffer.split() if len(args) < 2: self.completer.namespace.update(self.curframe.f_globals.copy()) self.completer.namespace.update(self.curframe.f_locals) return self.completer.complete(text, state) return None def filename(self, filename=None): """Return filename or the basename of that depending on the self.basename setting""" if filename is None: if self.mainpyfile: filename = self.mainpyfile else: return None if self.basename: return(os.path.basename(filename)) return filename def format_stack_entry(self, frame_lineno, lprefix=': ', include_location=True): """Format and return a stack entry gdb-style. Note: lprefix is not used. It is kept for compatibility. """ import repr as repr_mod frame, lineno = frame_lineno filename = self.filename(self.canonic_filename(frame)) s = '' if frame.f_code.co_name: s = frame.f_code.co_name else: s = "<lambda>" args, varargs, varkw, local_vars = inspect.getargvalues(frame) parms=inspect.formatargvalues(args, varargs, varkw, local_vars) if len(parms) >= self.maxargstrsize: parms = "%s...)" % parms[0:self.maxargstrsize] s += parms # ddd can't handle wrapped stack entries. # if len(s) >= 35: # s += "\n " if '__return__' in frame.f_locals: rv = frame.f_locals['__return__'] s += '->' s += repr_mod.repr(rv) add_quotes_around_file = True if include_location: if s == '?()': if is_exec_stmt(frame): s = 'in exec' exec_str = get_exec_string(frame.f_back) if exec_str != None: filename = exec_str add_quotes_around_file = False else: s = 'in file' else: s += ' called from file' if add_quotes_around_file: filename = "'%s'" % filename s += " %s at line %r" % (filename, lineno) return s # The following two methods can be called by clients to use # a debugger to debug a statement, given as a string. def run(self, cmd, globals=None, locals=None): """A copy of bdb's run but with a local variable added so we can find it it a call stack and hide it when desired (which is probably most of the time). """ breadcrumb = self.run if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) if not isinstance(cmd, types.CodeType): cmd = cmd+'\n' try: self.running = True try: exec cmd in globals, locals except bdb.BdbQuit: pass finally: self.quitting = 1 self.running = False sys.settrace(None) def reset(self): bdb.Bdb.reset(self) self.forget() def set_trace(self, frame=None): """Wrapper to accomodate different versions of Python""" if sys.version_info[0] == 2 and sys.version_info[1] >= 4: if frame is None: frame = self.curframe self.bdb_set_trace(self, frame) else: # older versions self.bdb_set_trace(self) def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function. Note argument_list isn't used. It is kept for compatibility""" self.stop_reason = 'call' if self._wait_for_mainpyfile: return if self.stop_here(frame): frame_count = count_frames(frame, Bdb.extra_call_frames) self.msg_nocr('--%sCall level %d' % ('-' * (2*frame_count), frame_count)) if frame_count >= 0: self.__print_call_params(frame) else: self.msg("") if self.linetrace or self.fntrace: self.__print_location_if_trace(frame) if not self.break_here(frame): return self.interaction(frame, None) def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" self.stop_reason = 'exception' # Remove any pending source lines. self.rcLines = [] frame.f_locals['__exception__'] = exc_type, exc_value if type(exc_type) == types.StringType: exc_type_name = exc_type else: exc_type_name = exc_type.__name__ self.msg("%s:%s" % (str(exc_type_name), str(self._saferepr(exc_value)))) self.interaction(frame, exc_traceback) def user_line(self, frame): """This function is called when we stop or break at this line. However it's *also* called when line OR function tracing is in effect. A little bit confusing and this code needs to be simplified.""" self.stop_reason = 'line' if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic_filename(frame) or inspect.getlineno(frame) <= 0): return self._wait_for_mainpyfile = False if self.stop_here(frame) or self.linetrace or self.fntrace: # Don't stop if we are looking at a def for which a breakpoint # has not been set. filename = self.filename(self.canonic_filename(frame)) line = linecache.getline(filename, inspect.getlineno(frame)) # No don't have a breakpoint. So we are either # stepping or here be of line tracing. if self.step_ignore > 0: # Don't stop this time, just note a step was done in # step count self.step_ignore -= 1 self.__print_location_if_trace(frame, False) return elif self.step_ignore < 0: # We are stepping only because we tracing self.__print_location_if_trace(frame, False) return if not self.break_here(frame): if is_def_stmt(line, frame) and not self.deftrace: self.__print_location_if_trace(frame, False) return elif self.fntrace: # The above test is a real hack. We need to clean # up this code. return else: if not self.break_here(frame) and self.step_ignore > 0: self.__print_location_if_trace(frame, False) self.step_ignore -= 1 return if self.bp_commands(frame): self.interaction(frame, None) def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" self.stop_reason = 'return' frame.f_locals['__return__'] = return_value frame_count = count_frames(frame, Bdb.extra_call_frames) if frame_count >= 0: self.msg_nocr("--%sReturn from level %d" % ('-' * (2*frame_count), frame_count)) if type(return_value) in [types.StringType, types.IntType, types.FloatType, types.BooleanType]: self.msg_nocr('=> %s' % repr(return_value)) self.msg('(%s)' % repr(type(return_value))) self.stop_reason = 'return' self.__print_location_if_trace(frame, False) if self.returnframe != None: self.interaction(frame, None)
{ "repo_name": "carlgao/lenga", "path": "images/lenny64-peon/usr/share/python-support/pydb/pydb/pydbbdb.py", "copies": "1", "size": "17883", "license": "mit", "hash": 2853046352200622000, "line_mean": 37.7917570499, "line_max": 79, "alpha_frac": 0.5442599116, "autogenerated": false, "ratio": 4.172421838544097, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5216681750144097, "avg_score": null, "num_lines": null }
""" Additional support for Pygments formatter. """ import pygments import pygments.formatter class OdtPygmentsFormatter(pygments.formatter.Formatter): def __init__(self, rststyle_function, escape_function): pygments.formatter.Formatter.__init__(self) self.rststyle_function = rststyle_function self.escape_function = escape_function def rststyle(self, name, parameters=( )): return self.rststyle_function(name, parameters) class OdtPygmentsProgFormatter(OdtPygmentsFormatter): def format(self, tokensource, outfile): tokenclass = pygments.token.Token for ttype, value in tokensource: value = self.escape_function(value) if ttype == tokenclass.Keyword: s2 = self.rststyle('codeblock-keyword') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Literal.String: s2 = self.rststyle('codeblock-string') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype in ( tokenclass.Literal.Number.Integer, tokenclass.Literal.Number.Integer.Long, tokenclass.Literal.Number.Float, tokenclass.Literal.Number.Hex, tokenclass.Literal.Number.Oct, tokenclass.Literal.Number, ): s2 = self.rststyle('codeblock-number') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Operator: s2 = self.rststyle('codeblock-operator') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Comment: s2 = self.rststyle('codeblock-comment') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Class: s2 = self.rststyle('codeblock-classname') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Function: s2 = self.rststyle('codeblock-functionname') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name: s2 = self.rststyle('codeblock-name') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) else: s1 = value outfile.write(s1) class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter): def format(self, tokensource, outfile): tokenclass = pygments.token.Token for ttype, value in tokensource: value = self.escape_function(value) if ttype == tokenclass.Keyword: s2 = self.rststyle('codeblock-keyword') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype in (tokenclass.Literal.String, tokenclass.Literal.String.Backtick, ): s2 = self.rststyle('codeblock-string') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Attribute: s2 = self.rststyle('codeblock-operator') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Comment: if value[-1] == '\n': s2 = self.rststyle('codeblock-comment') s1 = '<text:span text:style-name="%s">%s</text:span>\n' % \ (s2, value[:-1], ) else: s2 = self.rststyle('codeblock-comment') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Builtin: s2 = self.rststyle('codeblock-name') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) else: s1 = value outfile.write(s1)
{ "repo_name": "gauribhoite/personfinder", "path": "env/site-packages/docutils/writers/odf_odt/pygmentsformatter.py", "copies": "244", "size": "4671", "license": "apache-2.0", "hash": -6294248373775035000, "line_mean": 41.8532110092, "line_max": 79, "alpha_frac": 0.5099550417, "autogenerated": false, "ratio": 3.9451013513513513, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" Additional support for Pygments formatter. """ import pygments import pygments.formatter class OdtPygmentsFormatter(pygments.formatter.Formatter): def __init__(self, rststyle_function, escape_function): pygments.formatter.Formatter.__init__(self) self.rststyle_function = rststyle_function self.escape_function = escape_function def rststyle(self, name, parameters=( )): return self.rststyle_function(name, parameters) class OdtPygmentsProgFormatter(OdtPygmentsFormatter): def format(self, tokensource, outfile): tokenclass = pygments.token.Token for ttype, value in tokensource: value = self.escape_function(value) if ttype == tokenclass.Keyword: s2 = self.rststyle('codeblock-keyword') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Literal.String: s2 = self.rststyle('codeblock-string') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype in ( tokenclass.Literal.Number.Integer, tokenclass.Literal.Number.Integer.Long, tokenclass.Literal.Number.Float, tokenclass.Literal.Number.Hex, tokenclass.Literal.Number.Oct, tokenclass.Literal.Number, ): s2 = self.rststyle('codeblock-number') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Operator: s2 = self.rststyle('codeblock-operator') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Comment: s2 = self.rststyle('codeblock-comment') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Class: s2 = self.rststyle('codeblock-classname') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Function: s2 = self.rststyle('codeblock-functionname') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name: s2 = self.rststyle('codeblock-name') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) else: s1 = value outfile.write(s1) class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter): def format(self, tokensource, outfile): tokenclass = pygments.token.Token for ttype, value in tokensource: value = self.escape_function(value) if ttype == tokenclass.Keyword: s2 = self.rststyle('codeblock-keyword') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype in (tokenclass.Literal.String, tokenclass.Literal.String.Backtick, ): s2 = self.rststyle('codeblock-string') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Attribute: s2 = self.rststyle('codeblock-operator') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Comment: if value[-1] == '\n': s2 = self.rststyle('codeblock-comment') s1 = '<text:span text:style-name="%s">%s</text:span>\n' % \ (s2, value[:-1], ) else: s2 = self.rststyle('codeblock-comment') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) elif ttype == tokenclass.Name.Builtin: s2 = self.rststyle('codeblock-name') s1 = '<text:span text:style-name="%s">%s</text:span>' % \ (s2, value, ) else: s1 = value outfile.write(s1)
{ "repo_name": "rimbalinux/LMD3", "path": "docutils/writers/odf_odt/pygmentsformatter.py", "copies": "2", "size": "4780", "license": "bsd-3-clause", "hash": 7162684639399672000, "line_mean": 41.8532110092, "line_max": 79, "alpha_frac": 0.4983263598, "autogenerated": false, "ratio": 4.026958719460826, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5525285079260825, "avg_score": null, "num_lines": null }
""" Setup Peloton logging via the Python logging module. """ import peloton.utils.logging as pul import logging import logging.handlers import os import cPickle as pickle from peloton.utils import chop class NullHandler(logging.Handler): """ A logging handler that simply looses everying down the bit bucket...""" def __init__(self): logging.Handler.__init__(self) def emit(self, record): pass _LOG_HANDLERS_ = [] _DEFAULT_LEVEL_ = pul.ERROR def initialise(rootLoggerName='PSC', logLevel=None, logdir='', logfile='', logToConsole=True): global _DEFAULT_LEVEL_ if logLevel: _DEFAULT_LEVEL_ = logLevel else: logLevel = _DEFAULT_LEVEL_ formatter = logging.Formatter(pul._DEFAULT_FORMAT__) if logdir: # removes empty elements so allows for logdir being empty filePath = os.sep.join([i for i in [logdir, logfile] if i]) fileHandler = logging.handlers.TimedRotatingFileHandler(filePath, 'MIDNIGHT',1,7) fileHandler.setFormatter(formatter) _LOG_HANDLERS_.append(fileHandler) if logToConsole: logStreamHandler = logging.StreamHandler() logStreamHandler.setFormatter(formatter) _LOG_HANDLERS_.append(logStreamHandler) if not _LOG_HANDLERS_: # add a nullhandler for good measure _LOG_HANDLERS_.append(NullHandler()) logger = logging.getLogger() logger.name = rootLoggerName logger.setLevel(logLevel) for h in _LOG_HANDLERS_: logger.addHandler(h) def closeHandlers(): logger = logging.getLogger() while _LOG_HANDLERS_: logger.removeHandler(_LOG_HANDLERS_.pop()) def getLogger(name=''): l = logging.getLogger(name) l.setLevel(_DEFAULT_LEVEL_) return l class BusLogHandler(logging.Handler): """ A logging handler that puts log messages onto the message bus. """ def __init__(self, kernel): logging.Handler.__init__(self) self.kernel = kernel logging.getLogger().addHandler(self) def makeEvent(self, record): event={} keys = ['created', 'filename', 'funcName', 'levelname', 'lineno', 'module', 'name', 'pathname', 'process', 'threadName'] for key in keys: event[key] = getattr(record, key) # sometimes record has key msg, others message... not # sure why two versions of record exist. Same class # from same location (checked) if hasattr(record, 'message'): event['message'] = record.message else: event['message'] = record.msg return event def send(self, event): self.kernel.dispatcher.fireEvent(key="psc.logging", exchange='logging', **event) def emit(self, record): try: event = self.makeEvent(record) self.send(event) except Exception, ex: print(ex)
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/utils/logging/python_logger.py", "copies": "1", "size": "3194", "license": "bsd-3-clause", "hash": -8051107589625680000, "line_mean": 29.7115384615, "line_max": 94, "alpha_frac": 0.6164683782, "autogenerated": false, "ratio": 4.158854166666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5275322544866666, "avg_score": null, "num_lines": null }
# "Copyright (c) 2000-2003 The Regents of the University of California. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written agreement # is hereby granted, provided that the above copyright notice, the following # two paragraphs and the author appear in all copies of this software. # # IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT # OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY # OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS # ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO # PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." # @author Cory Sharp <cssharp@eecs.berkeley.edu> # @auther Shawn Schaffert import string, threading, MoteIF, Deluge from jpype import jimport _moteifCache = MoteIF.MoteIFCache() class Timer( object ) : def __init__( self , callback=None , period=0 , numFiring=0 , waitTime=0 ) : self.period = period #must be >= 0 self.waitTime = waitTime #must be >=0 self.numFiring = numFiring # 0 = forever, 1 = one-shot , 2+ = finite repeats self.callback = callback def __fireNext( self ) : if self.numFiring == 0 : self.timer = threading.Timer( self.period , self.__callback ).start() elif self.remainingFirings == 0 : self.timer = None else : self.timer = threading.Timer( self.period , self.__callback ).start() self.remainingFirings -= 1 def __callback( self ) : if self.stopTimer : self.timer = None else : self.__fireNext() if self.callback: self.callback() def __waitOver( self ) : self.__fireNext() def start( self ) : self.timer = None self.remainingFirings = self.numFiring self.stopTimer = False if self.waitTime > 0 : self.timer = threading.Timer( self.waitTime , self.__waitOver ).start() else : self.__fireNext() def cancel( self ) : self.stopTimer = True class MessageComm(Exception): pass class MessageComm( object ) : def __init__( self ) : self._moteifCache = _moteifCache self._connected = [] def connect( self , *moteComStr ) : for newMoteComStr in moteComStr : if newMoteComStr not in self._connected : self._moteifCache.get( newMoteComStr ) self._connected.append( newMoteComStr ) else : raise MessageCommError , "Already connected to " + newMoteComStr def disconnect( self , *moteComStr ) : for oldMoteComStr in moteComStr : if oldMoteComStr in self._connected : self._connected.remove( oldMoteComStr ) else : raise MessageCommError , "Not connected to " + oldMoteComStr def send( addr , msg , *moteComStr ) : if length( moteComStr ) == 0 : moteComStr = self._connected for mc in moteComStr : mote = self._moteifCache.get( mc ) mote.send( mote.TOS_BCAST_ADDR , msg.set_addr( addr ) ) # FIXME: send expects a Message, but only the # TOSMsg subclass has set_addr def register( msg , callback , *moteComStr ) : if length( moteComStr ) == 0 : moteComStr = self._connected for mc in moteComStr : mote.registerListener( msg , callback ) def unregister( msg , callback , *moteComStr ) : if length( moteComStr ) == 0 : moteComStr = self._connected for mc in moteComStr : mote.deregisterListener( msg , callback ) class Comm(object) : def __init__(self, source) : self._source = string.upper(source) self.deluge = Deluge.Deluge(self) def __getattribute__(self, name) : try : return object.__getattribute__(self,name) except : pass if name == "moteif" : return _moteifCache.get( self._source ) raise AttributeError, "%s has no attribute %s" % (self, name) def close(self) : if _moteifCache.isAlive(self._source) : _moteifCache.get(self._source).shutdown() return True return False class CommCache(object) : def __init__(self) : self._active = {} def get(self,source) : if not self.has(source) : self._active[source] = Comm(source) return self._active[source] def has(self,source) : return self._active.has_key(source) class PyTOS(object) : def __init__(self) : self._commCache = CommCache() def __getattribute__(self, name) : try : return object.__getattribute__(self,name) except : return self._commCache.get( name )
{ "repo_name": "fresskarma/tinyos-1.x", "path": "contrib/nestfe/python/pytos/PyTOS.py", "copies": "2", "size": "4969", "license": "bsd-3-clause", "hash": -7944662334493245000, "line_mean": 29.6728395062, "line_max": 108, "alpha_frac": 0.6568726102, "autogenerated": false, "ratio": 3.4821303433777153, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5139002953577715, "avg_score": null, "num_lines": null }
# $Id: qq.py 48 2008-05-27 17:31:15Z yardley $ # -*- coding: utf-8 -*- from dpkt import Packet # header_type QQ_HEADER_BASIC_FAMILY = 0x02 QQ_HEADER_P2P_FAMILY = 0x00 QQ_HEADER_03_FAMILY = 0x03 QQ_HEADER_04_FAMILY = 0x04 QQ_HEADER_05_FAMILY = 0x05 header_type_str = [ "QQ_HEADER_P2P_FAMILY", "Unknown Type", "QQ_HEADER_03_FAMILY", "QQ_HEADER_04_FAMILY", "QQ_HEADER_05_FAMILY", ] # command QQ_CMD_LOGOUT = 0x0001 QQ_CMD_KEEP_ALIVE = 0x0002 QQ_CMD_MODIFY_INFO = 0x0004 QQ_CMD_SEARCH_USER = 0x0005 QQ_CMD_GET_USER_INFO = 0x0006 QQ_CMD_ADD_FRIEND = 0x0009 QQ_CMD_DELETE_FRIEND = 0x000A QQ_CMD_ADD_FRIEND_AUTH = 0x000B QQ_CMD_CHANGE_STATUS = 0x000D QQ_CMD_ACK_SYS_MSG = 0x0012 QQ_CMD_SEND_IM = 0x0016 QQ_CMD_RECV_IM = 0x0017 QQ_CMD_REMOVE_SELF = 0x001C QQ_CMD_REQUEST_KEY = 0x001D QQ_CMD_LOGIN = 0x0022 QQ_CMD_GET_FRIEND_LIST = 0x0026 QQ_CMD_GET_ONLINE_OP = 0x0027 QQ_CMD_SEND_SMS = 0x002D QQ_CMD_CLUSTER_CMD = 0x0030 QQ_CMD_TEST = 0x0031 QQ_CMD_GROUP_DATA_OP = 0x003C QQ_CMD_UPLOAD_GROUP_FRIEND = 0x003D QQ_CMD_FRIEND_DATA_OP = 0x003E QQ_CMD_DOWNLOAD_GROUP_FRIEND = 0x0058 QQ_CMD_FRIEND_LEVEL_OP = 0x005C QQ_CMD_PRIVACY_DATA_OP = 0x005E QQ_CMD_CLUSTER_DATA_OP = 0x005F QQ_CMD_ADVANCED_SEARCH = 0x0061 QQ_CMD_REQUEST_LOGIN_TOKEN = 0x0062 QQ_CMD_USER_PROPERTY_OP = 0x0065 QQ_CMD_TEMP_SESSION_OP = 0x0066 QQ_CMD_SIGNATURE_OP = 0x0067 QQ_CMD_RECV_MSG_SYS = 0x0080 QQ_CMD_RECV_MSG_FRIEND_CHANGE_STATUS = 0x0081 QQ_CMD_WEATHER_OP = 0x00A6 QQ_CMD_ADD_FRIEND_EX = 0x00A7 QQ_CMD_AUTHORIZE = 0X00A8 QQ_CMD_UNKNOWN = 0xFFFF QQ_SUB_CMD_SEARCH_ME_BY_QQ_ONLY = 0x03 QQ_SUB_CMD_SHARE_GEOGRAPHY = 0x04 QQ_SUB_CMD_GET_FRIEND_LEVEL = 0x02 QQ_SUB_CMD_GET_CLUSTER_ONLINE_MEMBER = 0x01 QQ_05_CMD_REQUEST_AGENT = 0x0021 QQ_05_CMD_REQUEST_FACE = 0x0022 QQ_05_CMD_TRANSFER = 0x0023 QQ_05_CMD_REQUEST_BEGIN = 0x0026 QQ_CLUSTER_CMD_CREATE_CLUSTER = 0x01 QQ_CLUSTER_CMD_MODIFY_MEMBER = 0x02 QQ_CLUSTER_CMD_MODIFY_CLUSTER_INFO = 0x03 QQ_CLUSTER_CMD_GET_CLUSTER_INFO = 0x04 QQ_CLUSTER_CMD_ACTIVATE_CLUSTER = 0x05 QQ_CLUSTER_CMD_SEARCH_CLUSTER = 0x06 QQ_CLUSTER_CMD_JOIN_CLUSTER = 0x07 QQ_CLUSTER_CMD_JOIN_CLUSTER_AUTH = 0x08 QQ_CLUSTER_CMD_EXIT_CLUSTER = 0x09 QQ_CLUSTER_CMD_SEND_IM = 0x0A QQ_CLUSTER_CMD_GET_ONLINE_MEMBER = 0x0B QQ_CLUSTER_CMD_GET_MEMBER_INFO = 0x0C QQ_CLUSTER_CMD_MODIFY_CARD = 0x0E QQ_CLUSTER_CMD_GET_CARD_BATCH = 0x0F QQ_CLUSTER_CMD_GET_CARD = 0x10 QQ_CLUSTER_CMD_COMMIT_ORGANIZATION = 0x11 QQ_CLUSTER_CMD_UPDATE_ORGANIZATION = 0x12 QQ_CLUSTER_CMD_COMMIT_MEMBER_ORGANIZATION = 0x13 QQ_CLUSTER_CMD_GET_VERSION_ID = 0x19 QQ_CLUSTER_CMD_SEND_IM_EX = 0x1A QQ_CLUSTER_CMD_SET_ROLE = 0x1B QQ_CLUSTER_CMD_TRANSFER_ROLE = 0x1C QQ_CLUSTER_CMD_CREATE_TEMP = 0x30 QQ_CLUSTER_CMD_MODIFY_TEMP_MEMBER = 0x31 QQ_CLUSTER_CMD_EXIT_TEMP = 0x32 QQ_CLUSTER_CMD_GET_TEMP_INFO = 0x33 QQ_CLUSTER_CMD_MODIFY_TEMP_INFO = 0x34 QQ_CLUSTER_CMD_SEND_TEMP_IM = 0x35 QQ_CLUSTER_CMD_SUB_CLUSTER_OP = 0x36 QQ_CLUSTER_CMD_ACTIVATE_TEMP = 0x37 QQ_CLUSTER_SUB_CMD_ADD_MEMBER = 0x01 QQ_CLUSTER_SUB_CMD_REMOVE_MEMBER = 0x02 QQ_CLUSTER_SUB_CMD_GET_SUBJECT_LIST = 0x02 QQ_CLUSTER_SUB_CMD_GET_DIALOG_LIST = 0x01 QQ_SUB_CMD_GET_ONLINE_FRIEND = 0x2 QQ_SUB_CMD_GET_ONLINE_SERVICE = 0x3 QQ_SUB_CMD_UPLOAD_GROUP_NAME = 0x2 QQ_SUB_CMD_DOWNLOAD_GROUP_NAME = 0x1 QQ_SUB_CMD_SEND_TEMP_SESSION_IM = 0x01 QQ_SUB_CMD_BATCH_DOWNLOAD_FRIEND_REMARK = 0x0 QQ_SUB_CMD_UPLOAD_FRIEND_REMARK = 0x1 QQ_SUB_CMD_REMOVE_FRIEND_FROM_LIST = 0x2 QQ_SUB_CMD_DOWNLOAD_FRIEND_REMARK = 0x3 QQ_SUB_CMD_MODIFY_SIGNATURE = 0x01 QQ_SUB_CMD_DELETE_SIGNATURE = 0x02 QQ_SUB_CMD_GET_SIGNATURE = 0x03 QQ_SUB_CMD_GET_USER_PROPERTY = 0x01 QQ_SUB_CMD_GET_WEATHER = 0x01 QQ_FILE_CMD_HEART_BEAT = 0x0001 QQ_FILE_CMD_HEART_BEAT_ACK = 0x0002 QQ_FILE_CMD_TRANSFER_FINISHED = 0x0003 QQ_FILE_CMD_FILE_OP = 0x0007 QQ_FILE_CMD_FILE_OP_ACK = 0x0008 QQ_FILE_CMD_SENDER_SAY_HELLO = 0x0031 QQ_FILE_CMD_SENDER_SAY_HELLO_ACK = 0x0032 QQ_FILE_CMD_RECEIVER_SAY_HELLO = 0x0033 QQ_FILE_CMD_RECEIVER_SAY_HELLO_ACK = 0x0034 QQ_FILE_CMD_NOTIFY_IP_ACK = 0x003C QQ_FILE_CMD_PING = 0x003D QQ_FILE_CMD_PONG = 0x003E QQ_FILE_CMD_YES_I_AM_BEHIND_FIREWALL = 0x0040 QQ_FILE_CMD_REQUEST_AGENT = 0x0001 QQ_FILE_CMD_CHECK_IN = 0x0002 QQ_FILE_CMD_FORWARD = 0x0003 QQ_FILE_CMD_FORWARD_FINISHED = 0x0004 QQ_FILE_CMD_IT_IS_TIME = 0x0005 QQ_FILE_CMD_I_AM_READY = 0x0006 command_str = { 0x0001: "QQ_CMD_LOGOUT", 0x0002: "QQ_CMD_KEEP_ALIVE", 0x0004: "QQ_CMD_MODIFY_INFO", 0x0005: "QQ_CMD_SEARCH_USER", 0x0006: "QQ_CMD_GET_USER_INFO", 0x0009: "QQ_CMD_ADD_FRIEND", 0x000A: "QQ_CMD_DELETE_FRIEND", 0x000B: "QQ_CMD_ADD_FRIEND_AUTH", 0x000D: "QQ_CMD_CHANGE_STATUS", 0x0012: "QQ_CMD_ACK_SYS_MSG", 0x0016: "QQ_CMD_SEND_IM", 0x0017: "QQ_CMD_RECV_IM", 0x001C: "QQ_CMD_REMOVE_SELF", 0x001D: "QQ_CMD_REQUEST_KEY", 0x0022: "QQ_CMD_LOGIN", 0x0026: "QQ_CMD_GET_FRIEND_LIST", 0x0027: "QQ_CMD_GET_ONLINE_OP", 0x002D: "QQ_CMD_SEND_SMS", 0x0030: "QQ_CMD_CLUSTER_CMD", 0x0031: "QQ_CMD_TEST", 0x003C: "QQ_CMD_GROUP_DATA_OP", 0x003D: "QQ_CMD_UPLOAD_GROUP_FRIEND", 0x003E: "QQ_CMD_FRIEND_DATA_OP", 0x0058: "QQ_CMD_DOWNLOAD_GROUP_FRIEND", 0x005C: "QQ_CMD_FRIEND_LEVEL_OP", 0x005E: "QQ_CMD_PRIVACY_DATA_OP", 0x005F: "QQ_CMD_CLUSTER_DATA_OP", 0x0061: "QQ_CMD_ADVANCED_SEARCH", 0x0062: "QQ_CMD_REQUEST_LOGIN_TOKEN", 0x0065: "QQ_CMD_USER_PROPERTY_OP", 0x0066: "QQ_CMD_TEMP_SESSION_OP", 0x0067: "QQ_CMD_SIGNATURE_OP", 0x0080: "QQ_CMD_RECV_MSG_SYS", 0x0081: "QQ_CMD_RECV_MSG_FRIEND_CHANGE_STATUS", 0x00A6: "QQ_CMD_WEATHER_OP", 0x00A7: "QQ_CMD_ADD_FRIEND_EX", 0x00A8: "QQ_CMD_AUTHORIZE", 0xFFFF: "QQ_CMD_UNKNOWN", 0x0021: "_CMD_REQUEST_AGENT", 0x0022: "_CMD_REQUEST_FACE", 0x0023: "_CMD_TRANSFER", 0x0026: "_CMD_REQUEST_BEGIN", } class QQBasicPacket(Packet): __hdr__ = ( ('header_type', 'B', 2), ('source', 'H', 0), ('command', 'H', 0), ('sequence', 'H', 0), ('qqNum', 'L', 0), ) class QQ3Packet(Packet): __hdr__ = ( ('header_type', 'B', 3), ('command', 'B', 0), ('sequence', 'H', 0), ('unknown1', 'L', 0), ('unknown2', 'L', 0), ('unknown3', 'L', 0), ('unknown4', 'L', 0), ('unknown5', 'L', 0), ('unknown6', 'L', 0), ('unknown7', 'L', 0), ('unknown8', 'L', 0), ('unknown9', 'L', 0), ('unknown10', 'B', 1), ('unknown11', 'B', 0), ('unknown12', 'B', 0), ('source', 'H', 0), ('unknown13', 'B', 0), ) class QQ5Packet(Packet): __hdr__ = ( ('header_type', 'B', 5), ('source', 'H', 0), ('unknown', 'H', 0), ('command', 'H', 0), ('sequence', 'H', 0), ('qqNum', 'L', 0), )
{ "repo_name": "yangbh/dpkt", "path": "dpkt/qq.py", "copies": "6", "size": "6747", "license": "bsd-3-clause", "hash": 3247853693665956000, "line_mean": 29.1205357143, "line_max": 51, "alpha_frac": 0.6613309619, "autogenerated": false, "ratio": 2.274014155712841, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.593534511761284, "avg_score": null, "num_lines": null }
# $Id: qq.py 48 2008-05-27 17:31:15Z yardley $ # -*- coding: utf-8 -*- from __future__ import absolute_import from .dpkt import Packet # header_type QQ_HEADER_BASIC_FAMILY = 0x02 QQ_HEADER_P2P_FAMILY = 0x00 QQ_HEADER_03_FAMILY = 0x03 QQ_HEADER_04_FAMILY = 0x04 QQ_HEADER_05_FAMILY = 0x05 header_type_str = [ "QQ_HEADER_P2P_FAMILY", "Unknown Type", "QQ_HEADER_03_FAMILY", "QQ_HEADER_04_FAMILY", "QQ_HEADER_05_FAMILY", ] # command QQ_CMD_LOGOUT = 0x0001 QQ_CMD_KEEP_ALIVE = 0x0002 QQ_CMD_MODIFY_INFO = 0x0004 QQ_CMD_SEARCH_USER = 0x0005 QQ_CMD_GET_USER_INFO = 0x0006 QQ_CMD_ADD_FRIEND = 0x0009 QQ_CMD_DELETE_FRIEND = 0x000A QQ_CMD_ADD_FRIEND_AUTH = 0x000B QQ_CMD_CHANGE_STATUS = 0x000D QQ_CMD_ACK_SYS_MSG = 0x0012 QQ_CMD_SEND_IM = 0x0016 QQ_CMD_RECV_IM = 0x0017 QQ_CMD_REMOVE_SELF = 0x001C QQ_CMD_REQUEST_KEY = 0x001D QQ_CMD_LOGIN = 0x0022 QQ_CMD_GET_FRIEND_LIST = 0x0026 QQ_CMD_GET_ONLINE_OP = 0x0027 QQ_CMD_SEND_SMS = 0x002D QQ_CMD_CLUSTER_CMD = 0x0030 QQ_CMD_TEST = 0x0031 QQ_CMD_GROUP_DATA_OP = 0x003C QQ_CMD_UPLOAD_GROUP_FRIEND = 0x003D QQ_CMD_FRIEND_DATA_OP = 0x003E QQ_CMD_DOWNLOAD_GROUP_FRIEND = 0x0058 QQ_CMD_FRIEND_LEVEL_OP = 0x005C QQ_CMD_PRIVACY_DATA_OP = 0x005E QQ_CMD_CLUSTER_DATA_OP = 0x005F QQ_CMD_ADVANCED_SEARCH = 0x0061 QQ_CMD_REQUEST_LOGIN_TOKEN = 0x0062 QQ_CMD_USER_PROPERTY_OP = 0x0065 QQ_CMD_TEMP_SESSION_OP = 0x0066 QQ_CMD_SIGNATURE_OP = 0x0067 QQ_CMD_RECV_MSG_SYS = 0x0080 QQ_CMD_RECV_MSG_FRIEND_CHANGE_STATUS = 0x0081 QQ_CMD_WEATHER_OP = 0x00A6 QQ_CMD_ADD_FRIEND_EX = 0x00A7 QQ_CMD_AUTHORIZE = 0X00A8 QQ_CMD_UNKNOWN = 0xFFFF QQ_SUB_CMD_SEARCH_ME_BY_QQ_ONLY = 0x03 QQ_SUB_CMD_SHARE_GEOGRAPHY = 0x04 QQ_SUB_CMD_GET_FRIEND_LEVEL = 0x02 QQ_SUB_CMD_GET_CLUSTER_ONLINE_MEMBER = 0x01 QQ_05_CMD_REQUEST_AGENT = 0x0021 QQ_05_CMD_REQUEST_FACE = 0x0022 QQ_05_CMD_TRANSFER = 0x0023 QQ_05_CMD_REQUEST_BEGIN = 0x0026 QQ_CLUSTER_CMD_CREATE_CLUSTER = 0x01 QQ_CLUSTER_CMD_MODIFY_MEMBER = 0x02 QQ_CLUSTER_CMD_MODIFY_CLUSTER_INFO = 0x03 QQ_CLUSTER_CMD_GET_CLUSTER_INFO = 0x04 QQ_CLUSTER_CMD_ACTIVATE_CLUSTER = 0x05 QQ_CLUSTER_CMD_SEARCH_CLUSTER = 0x06 QQ_CLUSTER_CMD_JOIN_CLUSTER = 0x07 QQ_CLUSTER_CMD_JOIN_CLUSTER_AUTH = 0x08 QQ_CLUSTER_CMD_EXIT_CLUSTER = 0x09 QQ_CLUSTER_CMD_SEND_IM = 0x0A QQ_CLUSTER_CMD_GET_ONLINE_MEMBER = 0x0B QQ_CLUSTER_CMD_GET_MEMBER_INFO = 0x0C QQ_CLUSTER_CMD_MODIFY_CARD = 0x0E QQ_CLUSTER_CMD_GET_CARD_BATCH = 0x0F QQ_CLUSTER_CMD_GET_CARD = 0x10 QQ_CLUSTER_CMD_COMMIT_ORGANIZATION = 0x11 QQ_CLUSTER_CMD_UPDATE_ORGANIZATION = 0x12 QQ_CLUSTER_CMD_COMMIT_MEMBER_ORGANIZATION = 0x13 QQ_CLUSTER_CMD_GET_VERSION_ID = 0x19 QQ_CLUSTER_CMD_SEND_IM_EX = 0x1A QQ_CLUSTER_CMD_SET_ROLE = 0x1B QQ_CLUSTER_CMD_TRANSFER_ROLE = 0x1C QQ_CLUSTER_CMD_CREATE_TEMP = 0x30 QQ_CLUSTER_CMD_MODIFY_TEMP_MEMBER = 0x31 QQ_CLUSTER_CMD_EXIT_TEMP = 0x32 QQ_CLUSTER_CMD_GET_TEMP_INFO = 0x33 QQ_CLUSTER_CMD_MODIFY_TEMP_INFO = 0x34 QQ_CLUSTER_CMD_SEND_TEMP_IM = 0x35 QQ_CLUSTER_CMD_SUB_CLUSTER_OP = 0x36 QQ_CLUSTER_CMD_ACTIVATE_TEMP = 0x37 QQ_CLUSTER_SUB_CMD_ADD_MEMBER = 0x01 QQ_CLUSTER_SUB_CMD_REMOVE_MEMBER = 0x02 QQ_CLUSTER_SUB_CMD_GET_SUBJECT_LIST = 0x02 QQ_CLUSTER_SUB_CMD_GET_DIALOG_LIST = 0x01 QQ_SUB_CMD_GET_ONLINE_FRIEND = 0x2 QQ_SUB_CMD_GET_ONLINE_SERVICE = 0x3 QQ_SUB_CMD_UPLOAD_GROUP_NAME = 0x2 QQ_SUB_CMD_DOWNLOAD_GROUP_NAME = 0x1 QQ_SUB_CMD_SEND_TEMP_SESSION_IM = 0x01 QQ_SUB_CMD_BATCH_DOWNLOAD_FRIEND_REMARK = 0x0 QQ_SUB_CMD_UPLOAD_FRIEND_REMARK = 0x1 QQ_SUB_CMD_REMOVE_FRIEND_FROM_LIST = 0x2 QQ_SUB_CMD_DOWNLOAD_FRIEND_REMARK = 0x3 QQ_SUB_CMD_MODIFY_SIGNATURE = 0x01 QQ_SUB_CMD_DELETE_SIGNATURE = 0x02 QQ_SUB_CMD_GET_SIGNATURE = 0x03 QQ_SUB_CMD_GET_USER_PROPERTY = 0x01 QQ_SUB_CMD_GET_WEATHER = 0x01 QQ_FILE_CMD_HEART_BEAT = 0x0001 QQ_FILE_CMD_HEART_BEAT_ACK = 0x0002 QQ_FILE_CMD_TRANSFER_FINISHED = 0x0003 QQ_FILE_CMD_FILE_OP = 0x0007 QQ_FILE_CMD_FILE_OP_ACK = 0x0008 QQ_FILE_CMD_SENDER_SAY_HELLO = 0x0031 QQ_FILE_CMD_SENDER_SAY_HELLO_ACK = 0x0032 QQ_FILE_CMD_RECEIVER_SAY_HELLO = 0x0033 QQ_FILE_CMD_RECEIVER_SAY_HELLO_ACK = 0x0034 QQ_FILE_CMD_NOTIFY_IP_ACK = 0x003C QQ_FILE_CMD_PING = 0x003D QQ_FILE_CMD_PONG = 0x003E QQ_FILE_CMD_YES_I_AM_BEHIND_FIREWALL = 0x0040 QQ_FILE_CMD_REQUEST_AGENT = 0x0001 QQ_FILE_CMD_CHECK_IN = 0x0002 QQ_FILE_CMD_FORWARD = 0x0003 QQ_FILE_CMD_FORWARD_FINISHED = 0x0004 QQ_FILE_CMD_IT_IS_TIME = 0x0005 QQ_FILE_CMD_I_AM_READY = 0x0006 command_str = { 0x0001: "QQ_CMD_LOGOUT", 0x0002: "QQ_CMD_KEEP_ALIVE", 0x0004: "QQ_CMD_MODIFY_INFO", 0x0005: "QQ_CMD_SEARCH_USER", 0x0006: "QQ_CMD_GET_USER_INFO", 0x0009: "QQ_CMD_ADD_FRIEND", 0x000A: "QQ_CMD_DELETE_FRIEND", 0x000B: "QQ_CMD_ADD_FRIEND_AUTH", 0x000D: "QQ_CMD_CHANGE_STATUS", 0x0012: "QQ_CMD_ACK_SYS_MSG", 0x0016: "QQ_CMD_SEND_IM", 0x0017: "QQ_CMD_RECV_IM", 0x001C: "QQ_CMD_REMOVE_SELF", 0x001D: "QQ_CMD_REQUEST_KEY", 0x0022: "QQ_CMD_LOGIN", 0x0026: "QQ_CMD_GET_FRIEND_LIST", 0x0027: "QQ_CMD_GET_ONLINE_OP", 0x002D: "QQ_CMD_SEND_SMS", 0x0030: "QQ_CMD_CLUSTER_CMD", 0x0031: "QQ_CMD_TEST", 0x003C: "QQ_CMD_GROUP_DATA_OP", 0x003D: "QQ_CMD_UPLOAD_GROUP_FRIEND", 0x003E: "QQ_CMD_FRIEND_DATA_OP", 0x0058: "QQ_CMD_DOWNLOAD_GROUP_FRIEND", 0x005C: "QQ_CMD_FRIEND_LEVEL_OP", 0x005E: "QQ_CMD_PRIVACY_DATA_OP", 0x005F: "QQ_CMD_CLUSTER_DATA_OP", 0x0061: "QQ_CMD_ADVANCED_SEARCH", 0x0062: "QQ_CMD_REQUEST_LOGIN_TOKEN", 0x0065: "QQ_CMD_USER_PROPERTY_OP", 0x0066: "QQ_CMD_TEMP_SESSION_OP", 0x0067: "QQ_CMD_SIGNATURE_OP", 0x0080: "QQ_CMD_RECV_MSG_SYS", 0x0081: "QQ_CMD_RECV_MSG_FRIEND_CHANGE_STATUS", 0x00A6: "QQ_CMD_WEATHER_OP", 0x00A7: "QQ_CMD_ADD_FRIEND_EX", 0x00A8: "QQ_CMD_AUTHORIZE", 0xFFFF: "QQ_CMD_UNKNOWN", 0x0021: "_CMD_REQUEST_AGENT", 0x0022: "_CMD_REQUEST_FACE", 0x0023: "_CMD_TRANSFER", 0x0026: "_CMD_REQUEST_BEGIN", } class QQBasicPacket(Packet): __hdr__ = ( ('header_type', 'B', 2), ('source', 'H', 0), ('command', 'H', 0), ('sequence', 'H', 0), ('qqNum', 'L', 0), ) class QQ3Packet(Packet): __hdr__ = ( ('header_type', 'B', 3), ('command', 'B', 0), ('sequence', 'H', 0), ('unknown1', 'L', 0), ('unknown2', 'L', 0), ('unknown3', 'L', 0), ('unknown4', 'L', 0), ('unknown5', 'L', 0), ('unknown6', 'L', 0), ('unknown7', 'L', 0), ('unknown8', 'L', 0), ('unknown9', 'L', 0), ('unknown10', 'B', 1), ('unknown11', 'B', 0), ('unknown12', 'B', 0), ('source', 'H', 0), ('unknown13', 'B', 0), ) class QQ5Packet(Packet): __hdr__ = ( ('header_type', 'B', 5), ('source', 'H', 0), ('unknown', 'H', 0), ('command', 'H', 0), ('sequence', 'H', 0), ('qqNum', 'L', 0), )
{ "repo_name": "dimagol/trex-core", "path": "scripts/external_libs/dpkt-1.9.1/dpkt/qq.py", "copies": "3", "size": "6789", "license": "apache-2.0", "hash": -1543794029059876900, "line_mean": 28.9074889868, "line_max": 51, "alpha_frac": 0.6616585653, "autogenerated": false, "ratio": 2.2797179314976495, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44413764967976493, "avg_score": null, "num_lines": null }
# $Id: qq.py 48 2008-05-27 17:31:15Z yardley $ from dpkt import Packet # header_type QQ_HEADER_BASIC_FAMILY = 0x02 QQ_HEADER_P2P_FAMILY = 0x00 QQ_HEADER_03_FAMILY = 0x03 QQ_HEADER_04_FAMILY = 0x04 QQ_HEADER_05_FAMILY = 0x05 header_type_str = [ "QQ_HEADER_P2P_FAMILY", "Unknown Type", "QQ_HEADER_03_FAMILY", "QQ_HEADER_04_FAMILY", "QQ_HEADER_05_FAMILY", ] # command QQ_CMD_LOGOUT = 0x0001 QQ_CMD_KEEP_ALIVE = 0x0002 QQ_CMD_MODIFY_INFO = 0x0004 QQ_CMD_SEARCH_USER = 0x0005 QQ_CMD_GET_USER_INFO = 0x0006 QQ_CMD_ADD_FRIEND = 0x0009 QQ_CMD_DELETE_FRIEND = 0x000A QQ_CMD_ADD_FRIEND_AUTH = 0x000B QQ_CMD_CHANGE_STATUS = 0x000D QQ_CMD_ACK_SYS_MSG = 0x0012 QQ_CMD_SEND_IM = 0x0016 QQ_CMD_RECV_IM = 0x0017 QQ_CMD_REMOVE_SELF = 0x001C QQ_CMD_REQUEST_KEY = 0x001D QQ_CMD_LOGIN = 0x0022 QQ_CMD_GET_FRIEND_LIST = 0x0026 QQ_CMD_GET_ONLINE_OP = 0x0027 QQ_CMD_SEND_SMS = 0x002D QQ_CMD_CLUSTER_CMD = 0x0030 QQ_CMD_TEST = 0x0031 QQ_CMD_GROUP_DATA_OP = 0x003C QQ_CMD_UPLOAD_GROUP_FRIEND = 0x003D QQ_CMD_FRIEND_DATA_OP = 0x003E QQ_CMD_DOWNLOAD_GROUP_FRIEND = 0x0058 QQ_CMD_FRIEND_LEVEL_OP = 0x005C QQ_CMD_PRIVACY_DATA_OP = 0x005E QQ_CMD_CLUSTER_DATA_OP = 0x005F QQ_CMD_ADVANCED_SEARCH = 0x0061 QQ_CMD_REQUEST_LOGIN_TOKEN = 0x0062 QQ_CMD_USER_PROPERTY_OP = 0x0065 QQ_CMD_TEMP_SESSION_OP = 0x0066 QQ_CMD_SIGNATURE_OP = 0x0067 QQ_CMD_RECV_MSG_SYS = 0x0080 QQ_CMD_RECV_MSG_FRIEND_CHANGE_STATUS = 0x0081 QQ_CMD_WEATHER_OP = 0x00A6 QQ_CMD_ADD_FRIEND_EX = 0x00A7 QQ_CMD_AUTHORIZE = 0X00A8 QQ_CMD_UNKNOWN = 0xFFFF QQ_SUB_CMD_SEARCH_ME_BY_QQ_ONLY = 0x03 QQ_SUB_CMD_SHARE_GEOGRAPHY = 0x04 QQ_SUB_CMD_GET_FRIEND_LEVEL = 0x02 QQ_SUB_CMD_GET_CLUSTER_ONLINE_MEMBER = 0x01 QQ_05_CMD_REQUEST_AGENT = 0x0021 QQ_05_CMD_REQUEST_FACE = 0x0022 QQ_05_CMD_TRANSFER = 0x0023 QQ_05_CMD_REQUEST_BEGIN = 0x0026 QQ_CLUSTER_CMD_CREATE_CLUSTER= 0x01 QQ_CLUSTER_CMD_MODIFY_MEMBER= 0x02 QQ_CLUSTER_CMD_MODIFY_CLUSTER_INFO= 0x03 QQ_CLUSTER_CMD_GET_CLUSTER_INFO= 0x04 QQ_CLUSTER_CMD_ACTIVATE_CLUSTER= 0x05 QQ_CLUSTER_CMD_SEARCH_CLUSTER= 0x06 QQ_CLUSTER_CMD_JOIN_CLUSTER= 0x07 QQ_CLUSTER_CMD_JOIN_CLUSTER_AUTH= 0x08 QQ_CLUSTER_CMD_EXIT_CLUSTER= 0x09 QQ_CLUSTER_CMD_SEND_IM= 0x0A QQ_CLUSTER_CMD_GET_ONLINE_MEMBER= 0x0B QQ_CLUSTER_CMD_GET_MEMBER_INFO= 0x0C QQ_CLUSTER_CMD_MODIFY_CARD = 0x0E QQ_CLUSTER_CMD_GET_CARD_BATCH= 0x0F QQ_CLUSTER_CMD_GET_CARD = 0x10 QQ_CLUSTER_CMD_COMMIT_ORGANIZATION = 0x11 QQ_CLUSTER_CMD_UPDATE_ORGANIZATION= 0x12 QQ_CLUSTER_CMD_COMMIT_MEMBER_ORGANIZATION = 0x13 QQ_CLUSTER_CMD_GET_VERSION_ID= 0x19 QQ_CLUSTER_CMD_SEND_IM_EX = 0x1A QQ_CLUSTER_CMD_SET_ROLE = 0x1B QQ_CLUSTER_CMD_TRANSFER_ROLE = 0x1C QQ_CLUSTER_CMD_CREATE_TEMP = 0x30 QQ_CLUSTER_CMD_MODIFY_TEMP_MEMBER = 0x31 QQ_CLUSTER_CMD_EXIT_TEMP = 0x32 QQ_CLUSTER_CMD_GET_TEMP_INFO = 0x33 QQ_CLUSTER_CMD_MODIFY_TEMP_INFO = 0x34 QQ_CLUSTER_CMD_SEND_TEMP_IM = 0x35 QQ_CLUSTER_CMD_SUB_CLUSTER_OP = 0x36 QQ_CLUSTER_CMD_ACTIVATE_TEMP = 0x37 QQ_CLUSTER_SUB_CMD_ADD_MEMBER = 0x01 QQ_CLUSTER_SUB_CMD_REMOVE_MEMBER = 0x02 QQ_CLUSTER_SUB_CMD_GET_SUBJECT_LIST = 0x02 QQ_CLUSTER_SUB_CMD_GET_DIALOG_LIST = 0x01 QQ_SUB_CMD_GET_ONLINE_FRIEND = 0x2 QQ_SUB_CMD_GET_ONLINE_SERVICE = 0x3 QQ_SUB_CMD_UPLOAD_GROUP_NAME = 0x2 QQ_SUB_CMD_DOWNLOAD_GROUP_NAME = 0x1 QQ_SUB_CMD_SEND_TEMP_SESSION_IM = 0x01 QQ_SUB_CMD_BATCH_DOWNLOAD_FRIEND_REMARK = 0x0 QQ_SUB_CMD_UPLOAD_FRIEND_REMARK = 0x1 QQ_SUB_CMD_REMOVE_FRIEND_FROM_LIST = 0x2 QQ_SUB_CMD_DOWNLOAD_FRIEND_REMARK = 0x3 QQ_SUB_CMD_MODIFY_SIGNATURE = 0x01 QQ_SUB_CMD_DELETE_SIGNATURE = 0x02 QQ_SUB_CMD_GET_SIGNATURE = 0x03 QQ_SUB_CMD_GET_USER_PROPERTY = 0x01 QQ_SUB_CMD_GET_WEATHER = 0x01 QQ_FILE_CMD_HEART_BEAT = 0x0001 QQ_FILE_CMD_HEART_BEAT_ACK = 0x0002 QQ_FILE_CMD_TRANSFER_FINISHED = 0x0003 QQ_FILE_CMD_FILE_OP = 0x0007 QQ_FILE_CMD_FILE_OP_ACK = 0x0008 QQ_FILE_CMD_SENDER_SAY_HELLO = 0x0031 QQ_FILE_CMD_SENDER_SAY_HELLO_ACK = 0x0032 QQ_FILE_CMD_RECEIVER_SAY_HELLO = 0x0033 QQ_FILE_CMD_RECEIVER_SAY_HELLO_ACK = 0x0034 QQ_FILE_CMD_NOTIFY_IP_ACK = 0x003C QQ_FILE_CMD_PING = 0x003D QQ_FILE_CMD_PONG = 0x003E QQ_FILE_CMD_YES_I_AM_BEHIND_FIREWALL = 0x0040 QQ_FILE_CMD_REQUEST_AGENT = 0x0001 QQ_FILE_CMD_CHECK_IN = 0x0002 QQ_FILE_CMD_FORWARD = 0x0003 QQ_FILE_CMD_FORWARD_FINISHED = 0x0004 QQ_FILE_CMD_IT_IS_TIME = 0x0005 QQ_FILE_CMD_I_AM_READY = 0x0006 command_str = { 0x0001: "QQ_CMD_LOGOUT", 0x0002: "QQ_CMD_KEEP_ALIVE", 0x0004: "QQ_CMD_MODIFY_INFO", 0x0005: "QQ_CMD_SEARCH_USER", 0x0006: "QQ_CMD_GET_USER_INFO", 0x0009: "QQ_CMD_ADD_FRIEND", 0x000A: "QQ_CMD_DELETE_FRIEND", 0x000B: "QQ_CMD_ADD_FRIEND_AUTH", 0x000D: "QQ_CMD_CHANGE_STATUS", 0x0012: "QQ_CMD_ACK_SYS_MSG", 0x0016: "QQ_CMD_SEND_IM", 0x0017: "QQ_CMD_RECV_IM", 0x001C: "QQ_CMD_REMOVE_SELF", 0x001D: "QQ_CMD_REQUEST_KEY", 0x0022: "QQ_CMD_LOGIN", 0x0026: "QQ_CMD_GET_FRIEND_LIST", 0x0027: "QQ_CMD_GET_ONLINE_OP", 0x002D: "QQ_CMD_SEND_SMS", 0x0030: "QQ_CMD_CLUSTER_CMD", 0x0031: "QQ_CMD_TEST", 0x003C: "QQ_CMD_GROUP_DATA_OP", 0x003D: "QQ_CMD_UPLOAD_GROUP_FRIEND", 0x003E: "QQ_CMD_FRIEND_DATA_OP", 0x0058: "QQ_CMD_DOWNLOAD_GROUP_FRIEND", 0x005C: "QQ_CMD_FRIEND_LEVEL_OP", 0x005E: "QQ_CMD_PRIVACY_DATA_OP", 0x005F: "QQ_CMD_CLUSTER_DATA_OP", 0x0061: "QQ_CMD_ADVANCED_SEARCH", 0x0062: "QQ_CMD_REQUEST_LOGIN_TOKEN", 0x0065: "QQ_CMD_USER_PROPERTY_OP", 0x0066: "QQ_CMD_TEMP_SESSION_OP", 0x0067: "QQ_CMD_SIGNATURE_OP", 0x0080: "QQ_CMD_RECV_MSG_SYS", 0x0081: "QQ_CMD_RECV_MSG_FRIEND_CHANGE_STATUS", 0x00A6: "QQ_CMD_WEATHER_OP", 0x00A7: "QQ_CMD_ADD_FRIEND_EX", 0x00A8: "QQ_CMD_AUTHORIZE", 0xFFFF: "QQ_CMD_UNKNOWN", 0x0021: "_CMD_REQUEST_AGENT", 0x0022: "_CMD_REQUEST_FACE", 0x0023: "_CMD_TRANSFER", 0x0026: "_CMD_REQUEST_BEGIN", } class QQBasicPacket(Packet): __hdr__ = ( ('header_type', 'B', 2), ('source', 'H', 0), ('command', 'H', 0), ('sequence', 'H', 0), ('qqNum', 'L', 0), ) class QQ3Packet(Packet): __hdr__ = ( ('header_type', 'B', 3), ('command', 'B', 0), ('sequence', 'H', 0), ('unknown1', 'L', 0), ('unknown2', 'L', 0), ('unknown3', 'L', 0), ('unknown4', 'L', 0), ('unknown5', 'L', 0), ('unknown6', 'L', 0), ('unknown7', 'L', 0), ('unknown8', 'L', 0), ('unknown9', 'L', 0), ('unknown10', 'B', 1), ('unknown11', 'B', 0), ('unknown12', 'B', 0), ('source', 'H', 0), ('unknown13', 'B', 0), ) class QQ5Packet(Packet): __hdr__ = ( ('header_type', 'B', 5), ('source', 'H', 0), ('unknown', 'H', 0), ('command', 'H', 0), ('sequence', 'H', 0), ('qqNum', 'L', 0), )
{ "repo_name": "ashrith/dpkt", "path": "dpkt/qq.py", "copies": "15", "size": "6813", "license": "bsd-3-clause", "hash": 8849146160514403000, "line_mean": 29.4151785714, "line_max": 51, "alpha_frac": 0.653456627, "autogenerated": false, "ratio": 2.2763113932509187, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""A button, which switches its state in dependance of other buttons.""" from ToggleButton import ToggleButton from ButtonBase import ButtonBase from Constants import * from StyleInformation import StyleInformation import base class RadioButton (ToggleButton): """RadioButton (text, group=None) -> RadioButton A button widget class, which switches its state in depedance of others. The RadioButton can be grouped with other RadioButtons to allow a selection of a limited amount of choices. The constructor of the RadioButton allows you to assign it to an already existing group of RadioButtons. If no group is provided, the radio button will become a group. The RadioButton can be assigned to a group of RadioButtons by setting the 'group' attribute to the specified RadioButton group or by using the set_group() method. radiobutton.group = other_radio_button radiobutton.set_group (other_radio_button) The 'active' attribute and set_active() method allow you to toggle the state of the RadioButton. Whenever a RadioButton of a respective group will be activated, any other active RadioButton of that group will lose its state. radiobutton.active = True radiobutton.set_active (True) It is possible to add and remove RadioButtons to or from a specific group using the add_button() and remove_button() methods. radiobutton.add_button (other_radio_button) radiobutton.remove_button (other_radio_button) Note: It is possible to create nested sub groups of radio buttons by adding a radio button to another one, which is already in a group. Default action (invoked by activate()): See the ToggleButton class. Mnemonic action (invoked by activate_mnemonic()): See the ToggleButton class. Attributes: group - The radio button group the button belongs to. list - List of attached RadioButtons. """ def __init__ (self, text=None, group=None): ToggleButton.__init__ (self, text) # Group, the RadioButton is attached to. self._group = None # List for attached RadioButtons. self._list = [] if group: group.add_button (self) else: self._list.append (self) def set_group (self, group): """R.set_group (...) -> None Sets the group of RadioButtons, the RadioButton belongs to. Adds the RadioButton to a group, which causes the group to act as a RadioButton group, if it is not already one. If the button is already in another group, it will be removed from that group first. Raises a TypeError, if the passed argument does not inherit from the RadioButton class. """ if group and not isinstance (group, RadioButton): raise TypeError ("group must inherit from RadioButton") if self._group: if self._group != group: g = self._group self._group = None if self in g.list: g.remove_button (self) self._group = group if group: group.add_button (self) def set_active (self, active): """R.set_active (...) -> None Sets the state of the radio button. Sets the state of the RadioButton. if the active argument evaluates to True, the radio button will be activated and any other button of the same group deactivated. """ l = self.list or self.group.list if active: ToggleButton.set_active (self, active) for button in l: if button != self: button.set_active (False) else: found = False for button in l: if button.active and (button != self): found = True break if found: ToggleButton.set_active (self, active) def add_button (self, button): """R.add_button (...) -> None Adds a RadioButton to the group of RadioButtons. Adds a RadioButton to the RadioButtons causing it to become a RadioButton group, if it was not before. Raises a TypeError, if the passed argument does not inherit from the RadioButton class. """ if not isinstance (button, RadioButton): raise TypeError ("button must inherit from RadioButton") if button not in self.list: self.list.append (button) button.group = self def remove_button (self, button): """R.remove_button (...) -> None Removes a RadioButton from the group of RadioButtons. Removes a RadioButton from the group and sets its 'group' attribute to None. """ self.list.remove (button) button.group = None def draw_bg (self): """R.draw_bg () -> Surface Draws the RadioButton background surface and returns it. Creates the visible surface of the RadioButton and returns it to the caller. """ return base.GlobalStyle.engine.draw_radiobutton (self) def draw (self): """C.draw () -> None Draws the RadioButton surface. Creates the visible surface of the RadioButton and places a radio check and its Label on it. """ border_active = base.GlobalStyle.get_border_size \ (self.__class__, self.style, StyleInformation.get ("ACTIVE_BORDER")) ButtonBase.draw (self) if self.child: self.child.centery = self.image.get_rect ().centery self.child.x = self.padding + border_active + \ StyleInformation.get ("RADIO_SPACING") + \ StyleInformation.get ("RADIO_SIZE") self.image.blit (self.child.image, self.child.rect) def destroy (self): """R.destroy () -> None Destroys the RadioButton and removes it from its event system. """ if self.group: self.group.remove_button (self) else: while len (self.list) > 0: self.remove_button (self.list[0]) del self._list del self._group ToggleButton.destroy (self) group = property (lambda self: self._group, lambda self, var: self.set_group (var), doc = "The group the RadioButton belongs to.") list = property (lambda self: self._list, doc = "List of the attached RadionButtons.")
{ "repo_name": "prim/ocempgui", "path": "ocempgui/widgets/RadioButton.py", "copies": "1", "size": "8065", "license": "bsd-2-clause", "hash": -2420178175952565000, "line_mean": 36.1658986175, "line_max": 78, "alpha_frac": 0.6376937384, "autogenerated": false, "ratio": 4.510626398210291, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5648320136610291, "avg_score": null, "num_lines": null }
# $Id: radius.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Remote Authentication Dial-In User Service.""" from __future__ import absolute_import from . import dpkt from .compat import compat_ord # http://www.untruth.org/~josh/security/radius/radius-auth.html # RFC 2865 class RADIUS(dpkt.Packet): """Remote Authentication Dial-In User Service. TODO: Longer class information.... Attributes: __hdr__: Header fields of RADIUS. TODO. """ __hdr__ = ( ('code', 'B', 0), ('id', 'B', 0), ('len', 'H', 4), ('auth', '16s', b'') ) attrs = b'' def unpack(self, buf): dpkt.Packet.unpack(self, buf) self.attrs = parse_attrs(self.data) self.data = b'' def parse_attrs(buf): """Parse attributes buffer into a list of (type, data) tuples.""" attrs = [] while buf: t = compat_ord(buf[0]) l = compat_ord(buf[1]) if l < 2: break d, buf = buf[2:l], buf[l:] attrs.append((t, d)) return attrs # Codes RADIUS_ACCESS_REQUEST = 1 RADIUS_ACCESS_ACCEPT = 2 RADIUS_ACCESS_REJECT = 3 RADIUS_ACCT_REQUEST = 4 RADIUS_ACCT_RESPONSE = 5 RADIUS_ACCT_STATUS = 6 RADIUS_ACCESS_CHALLENGE = 11 # Attributes RADIUS_USER_NAME = 1 RADIUS_USER_PASSWORD = 2 RADIUS_CHAP_PASSWORD = 3 RADIUS_NAS_IP_ADDR = 4 RADIUS_NAS_PORT = 5 RADIUS_SERVICE_TYPE = 6 RADIUS_FRAMED_PROTOCOL = 7 RADIUS_FRAMED_IP_ADDR = 8 RADIUS_FRAMED_IP_NETMASK = 9 RADIUS_FRAMED_ROUTING = 10 RADIUS_FILTER_ID = 11 RADIUS_FRAMED_MTU = 12 RADIUS_FRAMED_COMPRESSION = 13 RADIUS_LOGIN_IP_HOST = 14 RADIUS_LOGIN_SERVICE = 15 RADIUS_LOGIN_TCP_PORT = 16 # unassigned RADIUS_REPLY_MESSAGE = 18 RADIUS_CALLBACK_NUMBER = 19 RADIUS_CALLBACK_ID = 20 # unassigned RADIUS_FRAMED_ROUTE = 22 RADIUS_FRAMED_IPX_NETWORK = 23 RADIUS_STATE = 24 RADIUS_CLASS = 25 RADIUS_VENDOR_SPECIFIC = 26 RADIUS_SESSION_TIMEOUT = 27 RADIUS_IDLE_TIMEOUT = 28 RADIUS_TERMINATION_ACTION = 29 RADIUS_CALLED_STATION_ID = 30 RADIUS_CALLING_STATION_ID = 31 RADIUS_NAS_ID = 32 RADIUS_PROXY_STATE = 33 RADIUS_LOGIN_LAT_SERVICE = 34 RADIUS_LOGIN_LAT_NODE = 35 RADIUS_LOGIN_LAT_GROUP = 36 RADIUS_FRAMED_ATALK_LINK = 37 RADIUS_FRAMED_ATALK_NETWORK = 38 RADIUS_FRAMED_ATALK_ZONE = 39 # 40-59 reserved for accounting RADIUS_CHAP_CHALLENGE = 60 RADIUS_NAS_PORT_TYPE = 61 RADIUS_PORT_LIMIT = 62 RADIUS_LOGIN_LAT_PORT = 63
{ "repo_name": "smutt/dpkt", "path": "dpkt/radius.py", "copies": "3", "size": "2403", "license": "bsd-3-clause", "hash": 3558894598638732300, "line_mean": 22.5588235294, "line_max": 69, "alpha_frac": 0.6604244694, "autogenerated": false, "ratio": 2.774826789838337, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9921980690464922, "avg_score": 0.002654113754683015, "num_lines": 102 }
# $Id: radius.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Remote Authentication Dial-In User Service.""" import dpkt # http://www.untruth.org/~josh/security/radius/radius-auth.html # RFC 2865 class RADIUS(dpkt.Packet): __hdr__ = ( ('code', 'B', 0), ('id', 'B', 0), ('len', 'H', 4), ('auth', '16s', '') ) attrs = '' def unpack(self, buf): dpkt.Packet.unpack(self, buf) self.attrs = parse_attrs(self.data) self.data = '' def parse_attrs(buf): """Parse attributes buffer into a list of (type, data) tuples.""" attrs = [] while buf: t = ord(buf[0]) l = ord(buf[1]) if l < 2: break d, buf = buf[2:l], buf[l:] attrs.append((t, d)) return attrs # Codes RADIUS_ACCESS_REQUEST = 1 RADIUS_ACCESS_ACCEPT = 2 RADIUS_ACCESS_REJECT = 3 RADIUS_ACCT_REQUEST = 4 RADIUS_ACCT_RESPONSE = 5 RADIUS_ACCT_STATUS = 6 RADIUS_ACCESS_CHALLENGE = 11 # Attributes RADIUS_USER_NAME = 1 RADIUS_USER_PASSWORD = 2 RADIUS_CHAP_PASSWORD = 3 RADIUS_NAS_IP_ADDR = 4 RADIUS_NAS_PORT = 5 RADIUS_SERVICE_TYPE = 6 RADIUS_FRAMED_PROTOCOL = 7 RADIUS_FRAMED_IP_ADDR = 8 RADIUS_FRAMED_IP_NETMASK = 9 RADIUS_FRAMED_ROUTING = 10 RADIUS_FILTER_ID = 11 RADIUS_FRAMED_MTU = 12 RADIUS_FRAMED_COMPRESSION = 13 RADIUS_LOGIN_IP_HOST = 14 RADIUS_LOGIN_SERVICE = 15 RADIUS_LOGIN_TCP_PORT = 16 # unassigned RADIUS_REPLY_MESSAGE = 18 RADIUS_CALLBACK_NUMBER = 19 RADIUS_CALLBACK_ID = 20 # unassigned RADIUS_FRAMED_ROUTE = 22 RADIUS_FRAMED_IPX_NETWORK = 23 RADIUS_STATE = 24 RADIUS_CLASS = 25 RADIUS_VENDOR_SPECIFIC = 26 RADIUS_SESSION_TIMEOUT = 27 RADIUS_IDLE_TIMEOUT = 28 RADIUS_TERMINATION_ACTION = 29 RADIUS_CALLED_STATION_ID = 30 RADIUS_CALLING_STATION_ID = 31 RADIUS_NAS_ID = 32 RADIUS_PROXY_STATE = 33 RADIUS_LOGIN_LAT_SERVICE = 34 RADIUS_LOGIN_LAT_NODE = 35 RADIUS_LOGIN_LAT_GROUP = 36 RADIUS_FRAMED_ATALK_LINK = 37 RADIUS_FRAMED_ATALK_NETWORK = 38 RADIUS_FRAMED_ATALK_ZONE = 39 # 40-59 reserved for accounting RADIUS_CHAP_CHALLENGE = 60 RADIUS_NAS_PORT_TYPE = 61 RADIUS_PORT_LIMIT = 62 RADIUS_LOGIN_LAT_PORT = 63
{ "repo_name": "jack8daniels2/dpkt", "path": "dpkt/radius.py", "copies": "6", "size": "2132", "license": "bsd-3-clause", "hash": -2434160725207229400, "line_mean": 22.4285714286, "line_max": 69, "alpha_frac": 0.6627579737, "autogenerated": false, "ratio": 2.66167290886392, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008805297266835728, "num_lines": 91 }
# $Id: radius.py 23 2006-11-08 15:45:33Z dugsong $ """Remote Authentication Dial-In User Service.""" import dpkt # http://www.untruth.org/~josh/security/radius/radius-auth.html # RFC 2865 class RADIUS(dpkt.Packet): __hdr__ = ( ('code', 'B', 0), ('id', 'B', 0), ('len', 'H', 4), ('auth', '16s', '') ) attrs = '' def unpack(self, buf): dpkt.Packet.unpack(self, buf) self.attrs = parse_attrs(self.data) self.data = '' def parse_attrs(buf): """Parse attributes buffer into a list of (type, data) tuples.""" attrs = [] while buf: t = ord(buf[0]) l = ord(buf[1]) if l < 2: break d, buf = buf[2:l], buf[l:] attrs.append((t, d)) return attrs # Codes RADIUS_ACCESS_REQUEST = 1 RADIUS_ACCESS_ACCEPT = 2 RADIUS_ACCESS_REJECT = 3 RADIUS_ACCT_REQUEST = 4 RADIUS_ACCT_RESPONSE = 5 RADIUS_ACCT_STATUS = 6 RADIUS_ACCESS_CHALLENGE = 11 # Attributes RADIUS_USER_NAME = 1 RADIUS_USER_PASSWORD = 2 RADIUS_CHAP_PASSWORD = 3 RADIUS_NAS_IP_ADDR = 4 RADIUS_NAS_PORT = 5 RADIUS_SERVICE_TYPE = 6 RADIUS_FRAMED_PROTOCOL = 7 RADIUS_FRAMED_IP_ADDR = 8 RADIUS_FRAMED_IP_NETMASK = 9 RADIUS_FRAMED_ROUTING = 10 RADIUS_FILTER_ID = 11 RADIUS_FRAMED_MTU = 12 RADIUS_FRAMED_COMPRESSION = 13 RADIUS_LOGIN_IP_HOST = 14 RADIUS_LOGIN_SERVICE = 15 RADIUS_LOGIN_TCP_PORT = 16 # unassigned RADIUS_REPLY_MESSAGE = 18 RADIUS_CALLBACK_NUMBER = 19 RADIUS_CALLBACK_ID = 20 # unassigned RADIUS_FRAMED_ROUTE = 22 RADIUS_FRAMED_IPX_NETWORK = 23 RADIUS_STATE = 24 RADIUS_CLASS = 25 RADIUS_VENDOR_SPECIFIC = 26 RADIUS_SESSION_TIMEOUT = 27 RADIUS_IDLE_TIMEOUT = 28 RADIUS_TERMINATION_ACTION = 29 RADIUS_CALLED_STATION_ID = 30 RADIUS_CALLING_STATION_ID = 31 RADIUS_NAS_ID = 32 RADIUS_PROXY_STATE = 33 RADIUS_LOGIN_LAT_SERVICE = 34 RADIUS_LOGIN_LAT_NODE = 35 RADIUS_LOGIN_LAT_GROUP = 36 RADIUS_FRAMED_ATALK_LINK = 37 RADIUS_FRAMED_ATALK_NETWORK = 38 RADIUS_FRAMED_ATALK_ZONE = 39 # 40-59 reserved for accounting RADIUS_CHAP_CHALLENGE = 60 RADIUS_NAS_PORT_TYPE = 61 RADIUS_PORT_LIMIT = 62 RADIUS_LOGIN_LAT_PORT = 63
{ "repo_name": "wofanli/trex-core", "path": "scripts/external_libs/dpkt-1.8.6/dpkt/radius.py", "copies": "15", "size": "2150", "license": "apache-2.0", "hash": 6606767442723667000, "line_mean": 23.4318181818, "line_max": 69, "alpha_frac": 0.6525581395, "autogenerated": false, "ratio": 2.4655963302752295, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""An abstract widget suitable for scale ranges and numerical adjustments. """ from BaseWidget import BaseWidget from Constants import * class Range (BaseWidget): """Range (minimum, maximum, step=1.0) -> Range An abstract widget class for scale ranges and numerical adjustments. The Range widget class is an abstract class suitable for widgets, which need numerical adjustment support, scale ranges and similar things. It supplies various attributes and methods to enable a widget for numerical input and range limit checks. A minimum range value (or lower limit) can be set using the 'minimum' attribute or set_minimum() method. It must not be greater than the set maximum value of the Range and any integer or float value are valid input for it. range.minimum = 1.7 range.set_minimum (5) In contrast of this, the 'maximum' attribute or set_maximum() method set the upper limit (or maximum range value) of the Range. As well as the 'minimum' attribute any integer or float are a valid value and must not be smaller than the minimum value of the Range. range.maximum = 123.45 range.set_maximum (100) To in- or decrease the Range value easily (in loops for example), the 'step' attribute or set_step() method can be used, which set the step value for the increase() and decrease() method. range.step = 0.5 range.set_step (10) while x > 100: range.increment () x -= 1 while y > 100: range.decrement () y -= 1 The current set value of the Range widget can be set or retrieved with the 'value' attribute or set_value() method. range.value = 10.0 range.set_value (100) Note: When you set the 'minimum' or 'maximum' attribute of the Range widget, the 'value' attribute will be automatically reset to the minimum or maximum value, if it is not within the range of the widget. Default action (invoked by activate()): None Mnemonic action (invoked by activate_mnemonic()): None Signals: SIG_VALCHANGED - Invoked, when the value of the Range changed. Attributes: minimum - The minimum value of the Range. maximum - The maximum value of the Range. step - Step range to use for in- or decreasing the Range. value - The current value of the Range. """ def __init__ (self, minimum, maximum, step=1.0): BaseWidget.__init__ (self) self._signals[SIG_VALCHANGED] = [] # Ranges and step value. self._minimum = minimum # Set the min and max values temporary self._maximum = maximum # and check them later. self._step = 0.0 self._value = 0.0 if minimum >= maximum: raise ValueError ("minimum must be smaller than maximum") self.set_step (step) def set_minimum (self, minimum): """R.set_minimum (...) -> None Sets the minimum value of the Range. Raises a TypeError, if the passed argument is not a float or integer. Raises a ValueError, if the passed argument is greater than the Range its maximum value. """ if type (minimum) not in (float, int): raise TypeError ("minimum must be a float or integer") if minimum > self.maximum: raise ValueError ("minimum must be smaller than %f" % self.maximum) self._minimum = minimum if minimum > self.value: # Adjust the current value on demand. self.value = minimum def set_maximum (self, maximum): """R.set_maximum (...) -> None Sets the maximum value of the Range. Raises a TypeError, if the passed argument is not a float or integer. Raises a ValueError, if the passed argument is smaller than the Range its minimum value. """ if type (maximum) not in (float, int): raise TypeError ("maximum must be a float or integer") if maximum < self.minimum: raise ValueError ("maximum must be greater than %f" % self.minimum) self._maximum = maximum if maximum < self.value: # Adjust the current value on demand. self.value = maximum def set_step (self, step=1.0): """R.set_step (...) -> None Sets the step range for in- or decreasing the Range value. Raises a TypeError, if the passed argument is not a float or integer. """ if type (step) not in (float, int): raise TypeError ("step must be a float or integer") self._step = step def set_value (self, value): """R.set_value (...) -> None Sets the current value of the Range. Sets the current value of the Range and raises a SIG_VALCHANGED event, if the new value differs from the old one. Raises a TypeError, if the passed argument is not a float or integer. Raises a ValueError, if the passed argument is not within the range of the Range its maximum and minimum value. """ if type (value) not in (float, int): raise TypeError ("value must be a float or integer") if (self.minimum > value) or (self.maximum < value): raise ValueError ("value must be in the range from %f to %f" % (self.minimum, self.maximum)) if value != self._value: self._value = value self.run_signal_handlers (SIG_VALCHANGED) self.dirty = True def increase (self): """R.increase () -> None Increases the current Range value by one step. """ val = self.value if val < self.maximum: val += self.step if val > self.maximum: val = self.maximum self.value = val def decrease (self): """R.decrease () -> None Decreases the current Range value by one step. """ val = self.value if val > self.minimum: val -= self.step if val < self.minimum: val = self.minimum self.value = val minimum = property (lambda self: self._minimum, lambda self, var: self.set_minimum (var), doc = "The minimum value of the Range.") maximum = property (lambda self: self._maximum, lambda self, var: self.set_maximum (var), doc = "The maximum value of the Range.") value = property (lambda self: self._value, lambda self, var: self.set_value (var), doc = "The current value of the Range.") step = property (lambda self: self._step, lambda self, var: self.set_step (var), doc = "The step range of the Range.")
{ "repo_name": "prim/ocempgui", "path": "ocempgui/widgets/Range.py", "copies": "1", "size": "8310", "license": "bsd-2-clause", "hash": 2551461976987325400, "line_mean": 36.264573991, "line_max": 79, "alpha_frac": 0.629843562, "autogenerated": false, "ratio": 4.453376205787781, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5583219767787782, "avg_score": null, "num_lines": null }
"""$Id: rdf.py 699 2006-09-25 02:01:18Z rubys $""" __author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>" __version__ = "$Revision: 699 $" __date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $" __copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim" from base import validatorBase from logging import * from validators import rdfAbout, noduplicates, text, eater from root import rss11_namespace as rss11_ns from extension import extension_everywhere rdfNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" # # rdf:RDF element. The valid children include "channel", "item", "textinput", "image" # class rdf(validatorBase,object): def do_rss090_channel(self): from channel import channel self.dispatcher.defaultNamespaces.append("http://my.netscape.com/rdf/simple/0.9/") return channel(), noduplicates() def do_channel(self): from channel import rss10Channel return rdfAbout(), rss10Channel(), noduplicates() def _is_090(self): return "http://my.netscape.com/rdf/simple/0.9/" in self.dispatcher.defaultNamespaces def _withAbout(self,v): if self._is_090(): return v else: return v, rdfAbout() def do_item(self): from item import rss10Item return self._withAbout(rss10Item()) def do_textinput(self): from textInput import textInput return self._withAbout(textInput()) def do_image(self): return self._withAbout(rss10Image()) def do_cc_License(self): return eater() def do_taxo_topic(self): return eater() def do_rdf_Description(self): return eater() def prevalidate(self): self.setFeedType(TYPE_RSS1) def validate(self): if not "channel" in self.children and not "rss090_channel" in self.children: self.log(MissingElement({"parent":self.name.replace('_',':'), "element":"channel"})) from validators import rfc2396_full class rss10Image(validatorBase, extension_everywhere): def validate(self): if not "title" in self.children: self.log(MissingTitle({"parent":self.name, "element":"title"})) if not "link" in self.children: self.log(MissingLink({"parent":self.name, "element":"link"})) if not "url" in self.children: self.log(MissingElement({"parent":self.name, "element":"url"})) def do_title(self): from image import title return title(), noduplicates() def do_link(self): return rfc2396_full(), noduplicates() def do_url(self): return rfc2396_full(), noduplicates() def do_dc_creator(self): return text() def do_dc_subject(self): return text() # duplicates allowed def do_dc_date(self): from validators import w3cdtf return w3cdtf(), noduplicates() def do_cc_license(self): return eater() # # This class performs RSS 1.x specific validations on extensions. # class rdfExtension(validatorBase): def __init__(self, qname, literal=False): validatorBase.__init__(self) self.qname=qname self.literal=literal def textOK(self): pass def setElement(self, name, attrs, parent): validatorBase.setElement(self, name, attrs, parent) if attrs.has_key((rdfNS,"parseType")): if attrs[(rdfNS,"parseType")] == "Literal": self.literal=True if not self.literal: # ensure no rss11 children if self.qname==rss11_ns: from logging import UndefinedElement self.log(UndefinedElement({"parent":parent.name, "element":name})) # no duplicate rdf:abouts if attrs.has_key((rdfNS,"about")): about = attrs[(rdfNS,"about")] if not "abouts" in self.dispatcher.__dict__: self.dispatcher.__dict__["abouts"] = [] if about in self.dispatcher.__dict__["abouts"]: self.log(DuplicateValue( {"parent":parent.name, "element":"rdf:about", "value":about})) else: self.dispatcher.__dict__["abouts"].append(about) def getExpectedAttrNames(self): # no rss11 attributes if self.literal or not self.attrs: return self.attrs.keys() return [(ns,n) for ns,n in self.attrs.keys() if ns!=rss11_ns] def validate(self): # rdflib 2.0.5 does not catch mixed content errors if self.value.strip() and self.children and not self.literal: self.log(InvalidRDF({"message":"mixed content"})) def startElementNS(self, name, qname, attrs): # ensure element is "namespace well formed" if name.find(':') != -1: from logging import MissingNamespace self.log(MissingNamespace({"parent":self.name, "element":name})) # ensure all attribute namespaces are properly defined for (namespace,attr) in attrs.keys(): if ':' in attr and not namespace: from logging import MissingNamespace self.log(MissingNamespace({"parent":self.name, "element":attr})) # eat children self.children.append((qname,name)) self.push(rdfExtension(qname, self.literal), name, attrs) def characters(self, string): if not self.literal: validatorBase.characters(self, string)
{ "repo_name": "slava-sh/NewsBlur", "path": "vendor/feedvalidator/rdf.py", "copies": "16", "size": "5026", "license": "mit", "hash": 3504104132879171000, "line_mean": 29.8343558282, "line_max": 94, "alpha_frac": 0.6689216076, "autogenerated": false, "ratio": 3.5519434628975266, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.019869308930083273, "num_lines": 163 }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
{ "repo_name": "spreeker/democracygame", "path": "external_apps/docutils-snapshot/build/lib/docutils/transforms/references.py", "copies": "2", "size": "35602", "license": "bsd-3-clause", "hash": -5906110973453113000, "line_mean": 38.734375, "line_max": 83, "alpha_frac": 0.529661255, "autogenerated": false, "ratio": 4.6308532778355875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00046633869446796296, "num_lines": 896 }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.transforms import Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) # register refname of the replacment node(s) # (needed for resolution of references) for node in subdef_copy.children: if isinstance(node, nodes.Referential): # HACK: verify refname attribute exists. # Test with docs/dev/todo.txt, see. |donate| if 'refname' in node: self.document.note_refname(node) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
{ "repo_name": "Soya93/Extract-Refactoring", "path": "python/helpers/py2only/docutils/transforms/references.py", "copies": "5", "size": "36066", "license": "apache-2.0", "hash": 8158379801457955000, "line_mean": 38.9844789357, "line_max": 83, "alpha_frac": 0.5283923917, "autogenerated": false, "ratio": 4.639310522253666, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7667702913953666, "avg_score": null, "num_lines": null }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) # register refname of the replacment node(s) # (needed for resolution of references) for node in subdef_copy.children: if isinstance(node, nodes.Referential): # HACK: verify refname attribute exists. # Test with docs/dev/todo.txt, see. |donate| if 'refname' in node: self.document.note_refname(node) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
{ "repo_name": "kool79/intellij-community", "path": "python/helpers/docutils/transforms/references.py", "copies": "57", "size": "36103", "license": "apache-2.0", "hash": -5396356238175250000, "line_mean": 38.9369469027, "line_max": 83, "alpha_frac": 0.5287095255, "autogenerated": false, "ratio": 4.638699730181164, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) # register refname of the replacment node(s) # (needed for resolution of references) for node in subdef_copy.children: if isinstance(node, nodes.Referential): # HACK: verify refname attribute exists. # Test with docs/dev/todo.txt, see. |donate| if 'refname' in node: self.document.note_refname(node) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
{ "repo_name": "rimbalinux/LMD3", "path": "docutils/transforms/references.py", "copies": "2", "size": "37007", "license": "bsd-3-clause", "hash": -2784785204825700400, "line_mean": 38.9369469027, "line_max": 83, "alpha_frac": 0.5157943092, "autogenerated": false, "ratio": 4.729329073482428, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6245123382682427, "avg_score": null, "num_lines": null }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.transforms import Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=True) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while True: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) if target['ids']: naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids.get(name) reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue if refid: del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star '\u2020', # dagger &dagger; '\u2021', # double dagger &Dagger; '\u00A7', # section mark &sect; '\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. '\u2660', # spade suit &spades; '\u2665', # heart suit &hearts; '\u2666', # diamond suit &diams; '\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while True: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) # register refname of the replacment node(s) # (needed for resolution of references) for node in subdef_copy.children: if isinstance(node, nodes.Referential): # HACK: verify refname attribute exists. # Test with docs/dev/todo.txt, see. |donate| if 'refname' in node: self.document.note_refname(node) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference(refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
{ "repo_name": "Soya93/Extract-Refactoring", "path": "python/helpers/py3only/docutils/transforms/references.py", "copies": "44", "size": "36116", "license": "apache-2.0", "hash": -2431087759323646500, "line_mean": 38.9955703212, "line_max": 83, "alpha_frac": 0.5282146417, "autogenerated": false, "ratio": 4.645144694533762, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=True) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while True: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if 'refid' in target: del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if target['refname'] in self.document.nameids: self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) if target['ids']: naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in utils.uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids.get(name) reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue if refid: del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while True: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if label in self.document.footnote_refs: reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if label in self.document.citation_refs: reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if refname in defs: key = refname else: normed_name = refname.lower() if normed_name in normed: key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if ('ltrim' in subdef.attributes or 'trim' in subdef.attributes): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if ('rtrim' in subdef.attributes or 'trim' in subdef.attributes): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) nested_ref['ref-origin'] = ref subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: # find original ref substitution which cased this error ref_origin = ref while ref_origin.hasattr('ref-origin'): ref_origin = ref_origin['ref-origin'] msg = self.document.reporter.error( 'Circular substitution definition referenced: ' '"%s".' % refname, base_node=ref_origin) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) # register refname of the replacment node(s) # (needed for resolution of references) for node in subdef_copy.children: if isinstance(node, nodes.Referential): # HACK: verify refname attribute exists. # Test with docs/dev/todo.txt, see. |donate| if 'refname' in node: self.document.note_refname(node) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if target['refuri'] not in notes: notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if ref['refuri'] not in notes: notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if refuri in notes: # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference(refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if refname in self.document.nameids: msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) try: prbid = node['ids'][0] except IndexError: prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference
{ "repo_name": "HesselTjeerdsma/Cyber-Physical-Pacman-Game", "path": "Algor/flask/lib/python2.7/site-packages/docutils/transforms/references.py", "copies": "7", "size": "36584", "license": "apache-2.0", "hash": -7792882722659829000, "line_mean": 39.0700985761, "line_max": 83, "alpha_frac": 0.5272796851, "autogenerated": false, "ratio": 4.650902618866006, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8678182303966004, "avg_score": null, "num_lines": null }
"""A specialized event manager and render group class for widgets.""" from pygame import display, Surface, event, QUIT, VIDEORESIZE, KMOD_SHIFT from pygame import K_TAB, KMOD_LALT, KMOD_RALT, KMOD_ALT, KMOD_CTRL, KMOD_RCTRL from pygame import KMOD_LCTRL, KMOD_RSHIFT, KMOD_LSHIFT, KEYUP, KEYDOWN, mouse from pygame import error as PygameError, time as PygameTime, Rect from ocempgui.events import EventManager, Event from ocempgui.access import IIndexable from ocempgui.draw import Complex, String from BaseWidget import BaseWidget from Constants import * import base class _LayerEventManager (EventManager): """_LayerEventManager (renderer) -> _LayerEventManager An event manager, that supports the layer system of the Renderer. """ def __init__ (self, renderer, layer): EventManager.__init__ (self) if not isinstance (renderer, Renderer): raise TypeError ("renderer must inherit from Renderer") self._renderer = renderer if type (layer) != int: raise TypeError ("layer must be an integer") self._layer = layer def emit_event (self, event): """L.emit_event (...) -> None Emits an event, which will be sent to the objects. Emits an event on a specific queue of the _LayerEventManager, which will be sent to the objects in that queue. If one of the receiving objects sets the 'handled' attribute of the event to True, the emission will stop immediately so that following objects will not receive the event. The method also will send specific events such as the SIG_FOCUSED event to _all_ event managers attched to the renderer. """ if event.signal == SIG_FOCUSED: re = self._renderer if isinstance (event.data, BaseWidget) and event.data.focus: re.active_layer = re._layers[event.data.depth] re._index_widget = event.data layers = re._layers.keys () for layer in layers: manager = re._layers.get (layer, (None, None, None))[2] if manager: if manager.event_grabber: manager.event_grabber.notify (event) return evlist = manager.queues.get (event.signal, []) for obj in evlist: obj.notify (event) if event.handled: break elif event.signal == SIG_DESTROYED: self._renderer.remove_widget (event.data) else: if self.event_grabber: self.event_grabber.notify (event) return evlist = self.queues.get (event.signal, []) for obj in evlist: obj.notify (event) if event.handled: break def emit_all (self, event): """L.emit_all (...) -> None Emits the passed event on all objects. """ evlist = self.queues.get (event.signal, []) for obj in evlist: obj.notify (event) def remove_object (self, obj, *signals): """L.remove_object (...) -> None Removes an object from the LayerEventManager. Removes the object from the queues passed as the 'signals' arguments. If 'signals' is None, the object will be removed from all queues of the EventManager. """ EventManager.remove_object (self, obj, *signals) if len (self) == 0: self._renderer._destroy_layer (self._layer) def grab_events (self, obj): """L.grab_events (...) -> None Sets an event grabber object for the LayerEventManager. Overrides the EventManager.grab_events() method and causes the Renderer, this manager is set for to send all events to distribute only to this instance. """ EventManager.grab_events (self, obj) if self.event_grabber: self._renderer._set_grab (self) else: self._renderer._set_grab (None) layer = property (lambda self: self._layer, doc = "The layer id, the event manager operates on.") class Renderer (IIndexable): """Renderer () -> Renderer A render engine, which can deal with events and sprites. The Renderer class incorporates an event management system based on the EventManager class from the ocempgui.events module and can render widgets based on the BaseWidget class. It contains several attributes and methods to create and manipulate a pygame window as well as interfaces to support a higher range of accessibility features such as keyboard navigation by implementing the IIndexable interfaces. The Renderer class can be used as standalone render engine and event loop for a pygame application or be integrated in an existing loop easily (which is exaplained below). The 'title' attribute and set_title() method will set the caption title of the pygame window. This works independant of if the Renderer works in a standalon or integrated mode. renderer.title = 'My title' renderer.set_title ('Another title') The 'screen' attribute and set_screen() method allow you to set up the background surface the Renderer shall use for blitting operations. This can be especially useful, if only portions of the complete visible screen contain elements, which should be handled by the Renderer and/or if the Renderer is not used as standalone render engine. If you instead want to use the Renderer as standalone, the create_screen() method should be used to create the pygame window with the desired size. # Screen already exists: renderer.screen = mainscreen renderer.set_screen (own_screen_portion) # Renderer will be used as standalone render engine with a pygame # window of 800x600 size. renderer.create_screen (800, 600) When using only a part of the screen it is important to adjust the Renderer's position, too, so that events, which require positional arguments (such as mouse movements, etc), can be translated correctly. This means, that when the Renderer's screen is blit a certain offset (x, y), its topleft position should be set to (x, y) as well: mainsurface.blit (renderer.screen, (10, 10)) renderer.topleft = 10, 10 As the Renderer exposes the attributes of its bound 'rect' attribute you can use the following attributes directly to modify its position: top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, width, height This however will NOT move the bound screen of the Renderer around. If the create_creen() method is used, resizing events will be recognized and resize the display accordingly. The 'support_resize' attribute and set_support_resize() method can influence this behaviour. It will be necessary to create the screen with the pygame.RESIZEABLE flag enabled in order to retrieve resizing events. 'support_resize' will be automatically enabled anyways, if create_screen() is used. # Create a resizeable window - no need to set support_resize. renderer.create_screen (200, 200, pygame.RESIZEABLE) # Enable resizing support, if the screen is assigned manually. renderer.support_resize = True renderer.set_support_resize (True) It is possible to set the background color of the set screen by adjusting the 'color' attribute or set_color() method. By default it uses a clear white color with the RBG value (255, 255, 255). It is possible to change that value by any time. It will be applied instantly. renderer.color = (255, 0, 0) renderer.set_color (100, 220, 100) The Renderer supports an update timer value (~ FPS setting), which defaults to 40. That means, that the timer will cause the default event system to poll events 40 times a second, which is a good value for most cases. On demand it can be adjusted using the 'timer' attribute or set_timer() method. Be careful with it. Higher values will cause higher CPU load. renderer.timer = 20 renderer.set_timer (100) It also supports different polling modes for events. The first polling mode relies on the timer value while the second uses an event based polling system. This means, that the second mode will completely ignore the timer value and instead wait for events to occur on the event queue. While the first mode is suitable for most FPS based applications and games, the latter one suits perfectly for event based ones. Note however, that the events to occur _MUST_ occur on the pygame event queue, not on those of the different EventManagers! The mode can be chosen by passing the Renderer.start() method an optional boolean argument, that determins, which mode should be used. True indicates the event based loop, False (the default) indicates the timer based loop. renderer.start () # Use the timer based polling. renderer.start (False) # Use the timer based polling. renderer.start (True) # Use the event based polling. The Renderer supports temporary locking the update routines by using the lock() and unlock() methods. Each lock() call however has to be followed by a call to unlock(). You can check whether the Renderer is currently locked by using its 'locked' attribute. renderer.lock () # Note that an unlock() has to follow. if renderer.locked: print 'The Renderer is currently locked' renderer.unlock () To speed up the mouse interaction behaviour, you can adjust the amount of mouse motion events to drop on each update the Renderer performs. This usually increases the overall speed while decreasing the exactness of mouse position related actions. You can adjust the amount of mouse motion events to drop using the 'drops' attribute and set_drops() method. renderer.drops = 10 # Drop each 10th mouse motion event on updates. renderer.set_drops (5) Keyboard navigation ------------------- The Renderer class implements keyboard navigation through the ocempgui.access.IIndexable interface class. It uses the TAB key for switching between attached objects of the currently active layer. Objects can be attached and removed using the add_index() and remove_index() method and will be automatically put into the correct layer (Note: objects inheriting from the BaseWidget class will do that automatically by default). Switching is done via the switch_index() method, which will be activated automatically by sending a KEYDOWN event with the TAB key as value. Objects which should be added to the navigation indexing, need to have a 'index' and 'sensitive' attribute and a set_focus() method, which receives a bool value as argument and returns True on successfully setting the focus or False otherwise. In case that False will be returned the method will try to set the focus on the next object. The index is needed for the order the objects shall be navigated through. Objects with a lower index will be focused earlier than objects with a higher index. If multiple objects with the same index are added, it cannot be guaranteed in which order they are activated. The active layer can be switched using the switch_layer() method, which will be activated automatically by sending a KEYDOWN event with the TAB key as value and CTRL as modifier. More information about the layer system can be found in the 'Layer system' section beneath. The Renderer supports automatic cycling through the objects and layers, which means, that if the end of the index list or layer list is reached it will start from the beginning of the respective list. Mnemonic support ---------------- The Renderer supports mnemonic keys (also known as hotkeys) for object activation through the <ALT><Key> combination. If it receives a KEYDOWN event, in which the ALT modifier is set, it will not escalate the event to its children, but instead loop over its indexing list in order to activate a matching child. As stated in 'Keyboard Navigation' the objects need to have a 'sensitive' attribute. Additionally they must have an activate_mnemonic() method, which receives a unicode as argument and returns True on successful mnemonic activation or False otherwise. If the widget's 'sensitive' attribute does not evaluate to True, the Renderer will not try to invoke the activate_mnemonic() method of the widget. Layer system ------------ The Renderer contains full z-axis support by using different layers, in which widgets will be kept and drawn. A higher layer index will cause widgets to be drawn on top of others with a lower index. The layer, in which a widget will be put, can be adjusted using the 'depth' attribute or set_depth() method of the BaseWidget class. Each layer stored in the Renderer is a tuple consisting of three values, * an index list, which keeps a list of indexable objects for that layer (see the section 'Keyboard navigation' above for more), * a widget list, which contains all the widgets and * a specialized EventManager subclass, that will deal with the events sent to the specific layer. The Renderer forwards received events to each layer starting with the currently active layer and then in order from the highest layer index (topmost layer) to the one with the lowest index (=lowest depth). The only exception from this behaviour is mouse input, which alaways will be sent in order from the highest layer index to the one with the lowest index. if the sent event is handled by any object within that particular layer and its 'handled' attribute is set to True, the event manager and Renderer will stop passing the event around, so that neither following widgets in that layer nor following layers will receive the event. Using the Renderer as standalone engine --------------------------------------- Using the Renderer as standalone engine is very simple. You usually have to type the following code to get it to work: renderer = Renderer () renderer.create_screen (width, height, optional_flags) renderer.title = 'Window caption title' renderer.color = (100, 200, 100) ... re.start () The first line will create a new Renderer object. The second creates a new pygame window with the passed width and height. The third and fourth line are not necessary, but useful and will set the window caption of the pygame window and the background color to use for the window. After those few steps you can add objects to the Renderer via the add_widget() method, use the inherited Group.add() method of the pygame.sprite system or the add_object() method from the inherited ocempgui.events.EventManager class. When you are done with that, an invocation of the start() method will run the event loop of the Renderer. Integrating the Renderer in an existing environment --------------------------------------------------- If an event loop and window already exists or an own event loop is necessary, the Renderer can be integrated into it with only a few lines of code. First you will need to set the screen, on which the Renderer should blit its objects: renderer = Renderer () renderer.screen = your_main_screen_or_surface Note, that if the assigned scren is a surface, which will be blit at a certain position x, y (e.g. mainscreen.blit (renderer.screen, (10, 10)), the Renderer's screen offset values have to be adjusted, too: Renderer.topleft = 10, 10 # Set both, x and y offset. Renderer.x = 10 # Only x offset. Renderer.y = 10 # Only y offset. See above for the necessity of it. Then you can send the events processed in your event loop to the Renderer and its objects via the distribute_events() method: def your_loop (): ... renderer.distribute_events (received_events) Attributes: title - The title caption to display on the pygame window. screen - The surface to draw on. timer - Speed of the event and update loop. Default is 40 fps. color - The background color of the screen. Default is (255, 255, 255). managers - The EventManager objects of the different layers. active_layer - The currently activated layer. show_layer_info - Indicates, whether the layer information should be shown on the screen when the layer is switched. support_resize - Indicates, whether resize events should be supported. Default is False and automatically set to True, if create_screen() is used. locked - Indicates, whether the Renderer is locked. drops - The mouse motion events to drop on each update. rect - The area occupied by the Renderer. x, y, ... - The Renderer allows to reposition itself through the width, ... various attributes offered by its rect attribute. size """ def __init__ (self): IIndexable.__init__ (self) self._title = None self._screen = None self._color = None self._background = None # _layers is a dictionary consisting of keys, that mark the # depth of a widget and a tuple value, that consists an index # list as first and a widget list (for the updating routines) as # second entry. # # layers = self._layers[0] # Get the entries for depth 0. # indices = layers[0] # widgets = layers[1] # # The _active_layer variable marks the currently active layer self._layers = { 0 : ([], [], _LayerEventManager (self, 0)) } self._activelayer = self._layers[0] self.__layerinfo = None self._showlayerinfo = False # Grabbed event manager for modal dialog locks. self._grabber = None # The currently indexed widget, that has the input focus. This is # layer independant to guarantee, that multiple widgets cannot # receive the input focus at the same time. self._indexwidget = None # Timer value for the event system. 40 frames per second should # be enough as default. self._timer = 40 # Tuple for double-click information. The tuple usually consists of: # self._mouseinfo[0] -> x coordinate of the mouse event pos. # self._mouseinfo[1] -> y coordinate of the mouse event pos. # self._mouseinfo[2] -> button id of the mouse event. # self._mouseinfo[3] -> tick amount since start. # See def _check_doubleclick () for details. self._mouseinfo = (0, 0, 0, 0) self.__updateevent = event.Event (SIG_UPDATED, data=self) # Indicates, the VIDEORESIZE events should be recognized. self._supportresize = False # Internal flags field for create_screen() calls, if # _supportresize is enabled. self.__flags = 0 # Screen offsets for partial screen assignments (Renderer is bound # to a surface instead to the whole pygame window. self._rect = Rect (0, 0, 0, 0) # Locking system. self._lock = 0 # The mouse motion events to drop on each update. self._drops = 0 def _get_rect (self): """W._get_rect () -> pygame.Rect Gets a copy of the widget's rect. """ return Rect (self._rect) def _get_rect_attr (self, attr): """R._get_rect_attr (...) -> var Gets the wanted attribute value from the underlying rect. """ return getattr (self._rect, attr) def _set_rect_attr (self, attr, value): """R._set_rect_attr (...) -> None Sets a specific attribute value on the underlying rect. Raises an AttributeError if the attr argument is the width, height or size. """ if attr in ("width", "height", "size"): # The width and height are protected! raise AttributeError ("%s attribute is read-only" % attr) setattr (self._rect, attr, value) def initclass (cls): """R.initclass () -> None Class method to expose the attributes of the own self.rect attribute. The method usually is called in the __init__.py script of the module. """ attributes = dir (Rect) for attr in attributes: if not attr.startswith ("__") and \ not callable (getattr (Rect, attr)): def get_attr (self, attr=attr): return cls._get_rect_attr (self, attr) def set_attr (self, value, attr=attr): return cls._set_rect_attr (self, attr, value) prop = property (get_attr, set_attr) setattr (cls, attr, prop) initclass = classmethod (initclass) def set_title (self, title): """R.set_title (...) -> None Sets the title to display on the pygame window. Raises a TypeError, if the passed argument is not a string or unicode. """ if type (title) not in (str, unicode): raise TypeError ("title must be a string or unicode") self._title = title display.set_caption (self._title) def set_screen (self, screen, x=0, y=0): """R.set_screen (...) -> None Sets the screen to use for the Renderer and its widgets. Sets the screen surface, the renderer will draw the widgets on (usually, you want this to be the entire screen). The optional x and y arguments specify, where the screen will be blit on the pygame display (this is important for event handling). Raises a TypeError, if the passed argument does not inherit from pygame.Surface. """ if screen and not isinstance (screen, Surface): raise TypeError ("screen must inherit from Surface") self._rect = screen.get_rect () self.topleft = x, y self._screen = screen self._create_bg () layers = filter (None, self._layers.values ()) for layer in layers: layer[2].emit_all (Event (SIG_SCREENCHANGED, screen)) self.refresh () def set_timer (self, timer=40): """R.set_timer (...) -> None Sets the speed of the event and update loop for the Renderer. Sets the speed for the internal event and update loop of the renderer. The higher the value, the faster the loop will go, which can cause a higher CPU usage. As a rough rule of thumb the timer value can be seen as the frames per second (FPS) value. A good value (also the default) is around 40 (~40 FPS) for modern computers. Raises a TypeError, if the passed argument is not a positive integer. """ if (type (timer) != int) or (timer <= 0): raise TypeError ("timer must be a positive integer > 0") self._timer = timer def set_show_layer_info (self, show): """R.set_show_layer_info (...) -> None Sets, whether the layer information should be shown or not. If set to true, the layer, which gets activated, will be shortly shown on the screen. """ self._showlayerinfo = show def set_color (self, color): """R.set_color (...) -> None Sets the background color of the attached screen. """ self._color = color if self.screen: self._create_bg () self.refresh () def set_support_resize (self, support): """R.set_support_resize (...) -> None Sets, whether resize event (VIDEORESIZE) should be supported. """ self._supportresize = support def _create_bg (self): """R._create_bg () -> None Creates the background for refreshing the window. """ if self.color != None: self.screen.fill (self.color) self._background = self.screen.copy () def create_screen (self, width, height, flags=0, depth=0): """R.create_screen (...) -> None Creates a new pygame window for the renderer. Creates a new pygame window with the given width and height and associates its entire surface with the 'screen' attribute to draw on. The optional flags argument can contain additional flags as specified by pygame.display.set_mode(). Raises a TypeError, if the passed arguments are not positive integers. Raises a ValueError, if the passed arguments are not positive integers greater than 0. """ if (type (width) != int) or (type (height) != int): raise TypeError ("width and height must be positive integers > 0") if (width <= 0) or (height <= 0): raise ValueError ("width and height must be positive integers > 0") self.support_resize = False # Suspend VIDEORESIZE events. self.screen = display.set_mode ((width, height), flags, depth) self.support_resize = True # Enable VIDEORESIZE events. self.__flags = flags self.refresh () def set_active_layer (self, layer): """R.set_active_layer (...) -> None Sets the currently active layer. Raises a TypeError, if the passed argument is not a valid layer index or key. """ if type (layer) == int: lay = self._layers.get (layer) if lay: show = self._activelayer != layer self._activelayer = lay if show: if self._showlayerinfo: self._create_layer (layer) self.switch_index () return elif type (layer) == tuple: layers = self._layers.values () if layer in layers: show = self._activelayer != layer self._activelayer = layer if show: if self._showlayerinfo: self._create_layer (layers.index (layer)) self.switch_index () return # Cause an exception, if the layer does not exist raise TypeError ("layer must be a valid key or value") def set_drops (self, drops): """R.set_drops (...) -> None Sets the amount of mouse motion events to drop on each update. Raises a TypeError, if the passed argument is not a positive integer. Raises a ValueError, if the passed argument is not a positive integer greater than or equal to 0. """ if type (drops) != int: raise TypeError ("drops must be a positive integer") if drops < 0: raise ValueError ("drops must be a positive integer") self._drops = drops def _set_grab (self, manager): """R._set_grab (manager) -> None Sets the event manager, which acts as grabber of all events. """ self._grabber = manager def lock (self): """R.lock () -> None Acquires a lock on the Renderer to suspend its updating methods. """ self._lock += 1 def unlock (self): """R.unlock () -> None Releases a previously set lock on the Renderer and updates it instantly. """ if self._lock > 0: self._lock -= 1 if self._lock == 0: self.refresh () def _add (self, widget): """R._add (...) -> None Adds a widget to the internal lists. """ layers = self._layers.get (widget.depth) if not layers: manager = _LayerEventManager (self, widget.depth) layers = ([], [], manager) self._layers[widget.depth] = layers # The first list is an indexing list used in add_index, the # second the widget list for updates, the third an event manager # for that layer. if widget in layers[1]: raise ValueError ("Widget %s already added" % widget) layers[1].append (widget) widget.manager = layers[2] def clear (self): """R.clear () -> None Removes and destroys all widgets and objects of the Renderer queues. """ keys = self._layers.keys () layers = self._layers rm_index = self.remove_index for key in keys: layer = layers[key] # Remove all widgets. widgets = layer[1][:] for w in widgets: w.destroy () if layers.has_key (key): # Remove all event capable objects. layer[2].clear () # Remove all indexed objects. rm_index (*layer[0]) def add_widget (self, *widgets): """R.add_widget (...) -> None Adds one or more widgets to the Renderer. Adds one or more widgets to the event system and the RenderGroup provided by the Renderer class. The widgets will be added to the internal indexing system for keyboard navigation, too. Raises a TypeError, if one of the passed arguments does not inherit from the BaseWidget class. """ for widget in widgets: if not isinstance (widget, BaseWidget): raise TypeError ("Widget %s must inherit from BaseWidget" % widget) self._add (widget) self.add_index (widget) widget.parent = self widget.update () def remove_widget (self, *widgets): """R.remove_widget (...) -> None Removes one or more widgets from the Renderer. Removes one or more widgets from the event and indexing systen of the Renderer class. Raises a TypeError, if one of the passed arguments does not inherit from the BaseWidget class. """ cleanup = False blit = self.screen.blit rects = [] for widget in widgets: layer = self._layers[widget.depth] if not isinstance (widget, BaseWidget): raise TypeError ("Widget %s must inherit from BaseWidget" % widget) if widget.parent == self: widget.parent = None if widget in layer[1]: # Not any widget is added to the widget queue (only the # topmost one), thus check, if the widget can be removed at # all. cleanup = True layer[1].remove (widget) blit (self._background, widget.rect, widget.rect) rects.append (widget.rect) self.remove_index (widget) widget.manager = None # Clean up. if cleanup: self._redraw_widgets (True, *rects) def add_index (self, *objects): """R.add_index (...) -> None Adds one or more widgets to the indexing system. The indexing system of the Renderer provides easy keyboard navigation using the TAB key. Widgets will by activated using their index, if they are added to to the indexing system. Raises a TypeError, if one of the passed arguments does not inherit from the BaseWidget class. """ for widget in objects: if not isinstance (widget, BaseWidget): raise TypeError ("Widget %s must inherit from BaseWidget" % widget) if widget.indexable not in (self, None): raise ValueError ("Widget already attched to an IIndexable") widget.indexable = self layers = self._layers.get (widget.depth) if not layers: manager = _LayerEventManager (self, widget.depth) layers = ([], [], manager) self._layers[widget.depth] = layers if widget not in layers[0]: layers[0].append (widget) # Sort the widget list, so we can access the index keys more # quickly. layers[0].sort (lambda x, y: cmp (x.index, y.index)) def remove_index (self, *objects): """R.remove_index (...) -> None Removes a widget from the indexing system. Removes a wigdget from the indexing system of the Renderer. """ index = None for widget in objects: index = self._layers[widget.depth][0] if widget in index: index.remove (widget) widget.indexable = None if widget == self._indexwidget: self._indexwidget = None if index and (len (index) == 0): self._destroy_layer (widget.depth) def _destroy_layer (self, index): """R._remove_layer (...) -> None Removes a layer from the Renderer, if it does not hold any objects. Removes a layer from the Renderer, if it does not hold any objects in each of its lists anymore. An exception is the layer with index 0, in which case this method will do nothing. """ if index == 0: return layer = self._layers.get (index) # Destroy Layer, if no object is contained in that list anymore. if (layer != None) and (len (layer[0]) == 0) and \ (len (layer[1]) == 0) and (len (layer[2]) == 0): if layer == self.active_layer: self.active_layer = self._layers[0] del self._layers[index] def update_index (self, *objects): """R.update_index (...) -> None Updates the indices for one or more widgets. """ layers = self._layers for w in objects: layers[w.depth][0].sort (lambda x, y: cmp (x.index, y.index)) def update_layer (self, oldlayer, widget): """R.update_layer (...) -> None Updates the layer for one or more widgets. """ old = self._layers[oldlayer] old[0].remove (widget) old[0].sort (lambda x, y: cmp (x.index, y.index)) old[1].remove (widget) old[2].remove (widget) new = self._layers[widget.depth] new[0].append (widget) new[0].sort (lambda x, y: cmp (x.index, y.index)) new[1].append (widget) new[2].add_object (widget) def _redraw_widgets (self, post=True, *rects): """R._redraw_widgets (...) -> None Redraws all widgets, that intersect with the rectangle list. Redraws all widgets, that intersect with the passed rectangles and raises the SIG_UPDATED event on demand. """ unique = [] append = unique.append # Clean doubled entries. for rect in rects: if rect not in unique: append (rect) bg = self._background blit = self.screen.blit layers = self._layers keys = self._layers.keys () keys.sort () redraw = [] append = redraw.append for index in keys: widgets = layers[index][1] for w in widgets: clip = w.rect.clip for rect in unique: intersect = clip (rect) if intersect.size != (0, 0): append ((w, intersect)) # We have the intersection list, blit it. redraw.sort (lambda x, y: cmp (x[0].depth, y[0].depth)) # Clean up. for w, i in redraw: blit (bg, i, i) # Blit changes. for w, i in redraw: blit (w.image, i.topleft, ((i.left - w.left, i.top - w.top), i.size)) display.update (unique) def update (self, **kwargs): """R.update (...) -> None Forces the Renderer to update its screen. """ if self.locked: return if not self.screen: return children = kwargs.get ("children", {}) dirty = [] dirty_append = dirty.append blit = self.screen.blit bg = self._background # Clear. for rect in children.values (): blit (bg, rect, rect) # Update dirty widgets. rect_widget = None items = children.items () for widget, rect in items: blit (bg, rect, rect) rect_widget = widget.rect blit (widget.image, rect_widget) if rect.colliderect (rect_widget): dirty_append (rect.union (rect_widget)) else: dirty_append (rect) dirty_append (rect_widget) # Update intersections. self._redraw_widgets (True, *dirty) # Post update. event.clear (SIG_TICK) if self.drops > 0: motions = event.get (MOUSEMOTION)[::self.drops] for m in motions: event.post (m) if not event.peek (SIG_UPDATED): event.post (self.__updateevent) def refresh (self): """R.refresh () -> None Causes the Renderer to do a complete screen refresh. In contrast to the update() method this method updates the whole screen area occupied by the Renderer and all its widgets. This is especially useful, if the size of the pygame window changes or the fullscreen mode is toggled. """ # If widgets have been added already, show them. layers = self._layers.values () for layer in layers: for widget in layer[1]: widget.update () if self.screen: display.flip () def start (self, wait=False): """R.start (...) -> None Starts the main loop of the Renderer. Start the main loop of the Renderer. Currently two different modes are supported: * Timer based event polling and distribution. This does not care about whether there are events or not, but suspends the loop for the set timer value on each run (known as FPS scaling). * Event based polling and distribution. This loop will only continue, if an event occurs on the queue and wait otherwise. """ if wait: self._synced_loop () else: self._loop () def switch_index (self, reverse=False): """R.switch_index (reverse=False) -> None Passes the input focus to the next or previous widget. Passes the input focus to the widget, which is the next or previous focusable after the one with the current focus. The default passing is to focus widget with the next higher or equal index set. If the reverse argument is set to True, the previous widget with a lower index is focused. """ indices = None if self._activelayer: indices = self._activelayer[0] else: indices = self._layers[0][0] if len (indices) == 0: return # Check, if at least one widget can be activated. widgets = [wid for wid in indices if wid.sensitive] if len (widgets) == 0: # None active here return # Get the widget with focus. try: self._indexwidget = [w for w in widgets if w.focus][0] except IndexError: # None is focused in that layer pass if self._indexwidget in widgets: pos = widgets.index (self._indexwidget) else: # index widget is not in the current layer. or not set pos = -1 # Reslice the list and traverse it. if not reverse: widgets = widgets[pos + 1:] + widgets[:pos + 1] else: widgets = widgets[pos:] + widgets[:pos] widgets.reverse () for wid in widgets: if (wid != self._indexwidget) and wid.set_focus (True): # Found a widget, which allows to be focused, exit. self._indexwidget = wid return def switch_layer (self): """R.switch_layer () -> None Passes the keyboard focus to the next layer. """ layers = self._layers.values () if len (layers) == 1: return index = 0 if self._activelayer: index = layers.index (self._activelayer) # Deactivate the current focus, if any. indices = self._activelayer[0] for w in indices: w.set_focus (False) if self._grabber: self._activelayer = layers[self._grabber.layer] else: # Reslice the list and traverse it. layers = layers[index + 1:] + layers[:index + 1] if (layers[0] != self._activelayer): self._activelayer = layers[0] # Focus the first index widget of that layer. self._indexwidget = None self.switch_index () if self._showlayerinfo: self._create_layer (layers.index (self._activelayer)) def _create_layer (self, index): """R._create_layer (...) -> None Creates a layer information surface. """ text = String.draw_string ("Layer: %d" % index, "sans", 18, True, (0, 0, 0)) r = text.get_rect () r.center = self.screen.get_rect ().center self.__layerinfo = Complex.FaderSurface (r.width, r.height) self.__layerinfo.blit (self.screen, (0, 0), r) self.__layerinfo.blit (text, (0, 0)) self.__layerinfo.step = -10 def _show_layer_info (self): """R._show_layer_info () -> None Shows the layer information on the main screen. """ rect = self.__layerinfo.get_rect () rect.center = self.screen.get_rect ().center if self.__layerinfo.alpha > 0: # Clean. self.screen.blit (self._background, rect, rect) self._redraw_widgets (False, (rect,)) # Redraw. self.__layerinfo.update () self.screen.blit (self.__layerinfo, rect) display.update (rect) else: # Clean up. self.__layerinfo = None self.screen.blit (self._background, rect, rect) self._redraw_widgets (False, (rect)) def _is_mod (self, mod): """R._is_mod (...) -> bool Determines, if the passed key value is a key modificator. Returns True if the pass key value is a key modificator (KMOD_ALT, KMOD_CTRL, etc.), False otherwise. """ return (mod & KMOD_ALT == KMOD_ALT) or \ (mod & KMOD_LALT == KMOD_LALT) or \ (mod & KMOD_RALT == KMOD_RALT) or \ (mod & KMOD_SHIFT == KMOD_SHIFT) or \ (mod & KMOD_LSHIFT == KMOD_LSHIFT) or \ (mod & KMOD_RSHIFT == KMOD_RSHIFT) or \ (mod & KMOD_RCTRL == KMOD_RCTRL) or \ (mod & KMOD_LCTRL == KMOD_LCTRL) or \ (mod & KMOD_CTRL) def _activate_mnemonic (self, event): """R._activate_mnemonic (...) -> None Activates the mnemonic key method of a widget. This method iterates over the widgets of the indexing system and tries to activate the mnemonic key method (activate_mnemonic()) of them. It breaks right after the first widget's method returned True. """ indices = self._activelayer[0] for wid in indices: if wid.sensitive and wid.activate_mnemonic (event.unicode): return def get_managers (self): """R.get_managers () -> dict Gets the event managers of the layers. Gets the event managers of the different layers as dictionary using the layer depth as key. """ keys = self._layers.keys () managers = {} for k in keys: managers[k] = self._layers[k][2] return managers def _get_layers (self, signal): """R._get_layers (signal) -> list Gets an ordered list of the layers. """ if signal not in SIGNALS_MOUSE: if self._activelayer: return [self._activelayer] # Get the key ids in reverse order keys = self._layers.keys () keys.sort () keys.reverse () self_layers = self._layers layers = [] for k in keys: layers.append (self_layers[k]) return layers def _check_doubleclick (self, event): """R._check_doubleclick (...) -> None Checks if the received event matches the criteria for a double-click. Checks if the received event matches the criteria for a double-click and emits a SIG_DOUBLICKED event, if it does. """ x, y = event.pos button = event.button ticks = PygameTime.get_ticks () elaps = ticks - self._mouseinfo[3] # Ignore button 4 and 5 for scroll wheels. if (button < 4) and (self._mouseinfo[2] == button): if elaps <= base.DoubleClickRate: if (x == self._mouseinfo[0]) and (y == self._mouseinfo[1]): ev = Event (SIG_DOUBLECLICKED, event) if not self._grabber: layers = self._get_layers (ev.signal) for layer in layers: if not ev.handled: layer[2].emit_event (ev) else: self._grabber.emit_event (ev) self._mouseinfo = (x, y, button, ticks) def distribute_events (self, *events): """R.distribute_events (...) -> bool Distributes one ore more events to the widgets of the Renderer. The method distributes the received events to the attached objects. If the events contain KEYDOWN events, the IIndexable interface method for keyboard navigation will be invoked before the Renderer tries to send them to its objects. The method returns False, as soon as it receives a QUIT event. If all received events passed it successfully, True will be returned. """ resize = self.support_resize ismod = self._is_mod pos = None for event in events: ev = None pos = None etype = event.type if etype == QUIT: return False elif (etype == VIDEORESIZE) and resize: self.create_screen (event.w, event.h, self.__flags) elif etype == MOUSEMOTION: pos = event.pos # Check, whether the mouse is located within the assigned # area. if (pos[0] < self.left) or (pos[0] > self.right) or \ (pos[1] < self.top) or (pos[1] > self.bottom): continue event.dict["pos"] = event.pos[0] - self.x, \ event.pos[1] - self.y ev = Event (SIG_MOUSEMOVE, event) elif etype == MOUSEBUTTONDOWN: pos = event.pos # Check, whether the mouse is located within the assigned # area. if (pos[0] < self.left) or (pos[0] > self.right) or \ (pos[1] < self.top) or (pos[1] > self.bottom): continue event.dict["pos"] = event.pos[0] - self.x, \ event.pos[1] - self.y ev = Event (SIG_MOUSEDOWN, event) elif etype == MOUSEBUTTONUP: pos = event.pos # Check, whether the mouse is located within the assigned # area. if (pos[0] < self.left) or (pos[0] > self.right) or \ (pos[1] < self.top) or (pos[1] > self.bottom): continue event.dict["pos"] = event.pos[0] - self.x, \ event.pos[1] - self.y self._check_doubleclick (event) ev = Event (SIG_MOUSEUP, event) elif etype == KEYDOWN: # Check, if it is the TAB key and call the indexing # methods on demand. if event.key == K_TAB: if not ismod (event.mod): # Cycle through the widgets of the current layer. self.switch_index () elif event.mod & KMOD_SHIFT: self.switch_index (True) elif event.mod & KMOD_CTRL: # Cycle through the layers. self.switch_layer () elif event.mod & KMOD_LALT == KMOD_LALT: self._activate_mnemonic (event) else: ev = Event (SIG_KEYDOWN, event) elif etype == KEYUP: ev = Event (SIG_KEYUP, event) else: # We also will distribute any other event. ev = Event (etype, event) if ev: if ev.signal in (SIG_TICK, SIG_SCREENCHANGED): layers = filter (None, self._layers.values ()) for layer in layers: layer[2].emit_all (ev) elif not self._grabber: layers = filter (None, self._get_layers (ev.signal)) for layer in layers: if not ev.handled: layer[2].emit_event (ev) else: self._grabber.emit_event (ev) # Restore the original position. if pos != None: event.dict["pos"] = pos return True def _loop (self): """R._loop () -> None A main event loop, which uses a timer based polling. Main event loop of the Renderer. This loop hooks up on the event loop of pygame and distributes all its events to the attached objects. It uses a timer based polling mechanism instead of waiting for events. """ # Emit the tick event every 10 ms. PygameTime.set_timer (SIG_TICK, 10) delay = PygameTime.delay event_get = event.get pump = event.pump while True: pump () # Get events and distribute them. events = event_get () if not self.distribute_events (*events): return # QUIT event if self.timer > 0: delay (1000 / self.timer) if self.__layerinfo: self._show_layer_info () def _synced_loop (self): """R._synced_loop () -> None A main event loop, which uses an event based polling. Main event loop of the Renderer. This loop hooks up on the event loop of pygame and distributes all its events to the attached objects. It waits for an event to occur on the queues before it does further processing. It ignores the Renderer.timer setting. """ # Emit the tick event every 10 ms. PygameTime.set_timer (SIG_TICK, 10) event_wait = event.wait pump = event.pump while True: pump () # Get an event and distribute it. if not self.distribute_events (event_wait ()): return # QUIT event if self.__layerinfo: self._show_layer_info () locked = property (lambda self: self._lock > 0, doc = "Indicates, whether the Renderer is locked.") title = property (lambda self: self._title, lambda self, var: self.set_title (var), doc = "The title of the pygame window.") screen = property (lambda self: self._screen, lambda self, var: self.set_screen (var), doc = "The screen to draw on.") timer = property (lambda self: self._timer, lambda self, var: self.set_timer (var), doc = "The speed of the event and update loop.") color = property (lambda self: self._color, lambda self, var: self.set_color (var), doc = "The background color of the pygame window.") active_layer = property (lambda self: self._activelayer, lambda self, var: self.set_active_layer (var), doc = "The active layer on the pygame window.") show_layer_info = property (lambda self: self._showlayerinfo, lambda self, var: self.set_show_layer_info (var), doc = "Indicates, whether the layer info should "\ "be shown when changing the layer.") support_resize = property (lambda self: self._supportresize, lambda self, var: self.set_support_resize (var), doc = "Indicates, whether resize events "\ "should be supported.") managers = property (lambda self: self.get_managers (), doc = "Tuple containing the available " \ "EventManagers for the different layers.") rect = property (lambda self: self._get_rect (), doc = "The area occupied by the Renderer.") drops = property (lambda self: self._drops, lambda self, var: self.set_drops (var), doc = "The mouse motion events to drop on each update.")
{ "repo_name": "prim/ocempgui", "path": "ocempgui/widgets/Renderer.py", "copies": "1", "size": "56115", "license": "bsd-2-clause", "hash": -9000527306651276000, "line_mean": 37.1994554118, "line_max": 79, "alpha_frac": 0.5864742048, "autogenerated": false, "ratio": 4.46491088478676, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009399744886212102, "num_lines": 1469 }
from twisted.internet import reactor from twisted.internet.error import CannotListenError from twisted.web import server from twisted.web import resource from twisted.web.static import FileTransfer from peloton.adapters import AbstractPelotonAdapter from peloton.adapters.xmlrpc import PelotonXMLRPCHandler from peloton.coreio import PelotonRequestInterface from peloton.utils.config import locateService from peloton.exceptions import ServiceError import os binaryFileMimeTypes = {'.png':'image/PNG','.jpg':'image/JPEG', '.jpeg':'image/JPEG','.gif':'image/GIF','.bmp':'image/BMP', '.pdf':'application/PDF', '.zip':'application/x-zip-compressed', '.tgz':'application/x-gzip'} plainFileMimeTypes = {'.css':'text/css', '.html' : 'text/html; charset=UTF-8', '.js':'text/javascript'} class PelotonHTTPAdapter(AbstractPelotonAdapter, resource.Resource): """ The HTTP adapter provides for accessing methods over HTTP and receiving the results in a desired format. The main interface is rest-like but it also provides XMLRPC. Strictly speaking this isn't true rest: URIs refer to services not resources and session tracking is used. But... well... """ isLeaf = True def __init__(self, kernel): AbstractPelotonAdapter.__init__(self, kernel, 'HTTP Adapter') resource.Resource.__init__(self) self.logger = kernel.logger self.requestInterface = PelotonRequestInterface(kernel) self.xmlrpcHandler = PelotonXMLRPCHandler(kernel) # setup info template loader from peloton.utils.transforms import template source=os.path.split(__file__)[0].split(os.sep) source.extend(['templates','request_info.html.genshi']) self.infoTemplate = template({}, "/".join(source)) def start(self): """ Implement to initialise the adapter. This method must also hook this adapter into the reactor, probably calling reactor.listenTCP or adding itself to another protocol as a resource (this is the case for most HTTP based adapters).""" try: self.connection = reactor.listenTCP(self.kernel.settings.httpPort, server.Site(self), interface=self.kernel.profile.bind_interface) except CannotListenError: self.kernel.logger.info("Cannot start HTTP interface: port %s in use" % \ self.kernel.settings.httpPort) self.connection = None def render_GET(self, request): return self.render_POST(request) def render_POST(self, request): if request.postpath and request.postpath[0] == "RPC2": return self.xmlrpcHandler._resource.render(request) elif request.postpath and request.postpath[0] == "static": profile, _ = \ self.kernel.serviceLibrary.getProfile(request.postpath[1]) resourceRoot = profile['resourceRoot'] self.deliverStaticContent(resourceRoot, request.postpath[2:], request) elif request.postpath and request.postpath[0] == "fireEvent": self.fireEvent(request.postpath[1:], request) elif request.postpath and request.postpath[0] == "inspect": resp = self.infoTemplate({'rq':request}, {}) self.deferredResponse(resp, 'html', None, 'text/html',request) elif request.postpath and request.postpath[0] == "favicon.ico": self.returnFavicon(request) else: if request.postpath[-1] == '': request.postpath = request.postpath[:-1] try: service, method = request.postpath[:2] except ValueError: if len(request.postpath) == 1: service = request.postpath[0] method = 'index' else: raise ServiceError("Method or service not found for %s " % str(request.postpath)) split = method.split('.') if len(split)==1: target = 'html' else: method, target = split args = request.postpath[2:] kwargs={} # JSON requests which set the callback argument will get a JSONP formatted response callbackName = None for k,v in request.args.items(): self.kernel.logger.debug("Key %s value %s" % (k,v)) if target == 'json' and k == 'callback': callbackName = v[0] elif len(v) == 1: kwargs[k] = v[0] else: kwargs[k] = v self.kernel.logger.info("Callback name %s" % callbackName) try: profile, _ = self.kernel.serviceLibrary.getProfile(service) mimeType = profile['methods'][method]['properties']['mimetype.%s'%target] except: try: mimeType = {'html':'text/html', 'xml':'text/xml', 'json':'text/plain', 'raw':'text/plain'}[target] except KeyError: mimeType = 'text/plain' sessionId="TOBESORTED" d = self.requestInterface.public_call(sessionId, target, service, method, args, kwargs ) d.addCallback(self.deferredResponse, target, callbackName, mimeType, request) d.addErrback(self.deferredError, target, request) return server.NOT_DONE_YET def fireEvent(self, args, request): """ Fire an event on the message bus. Payload is the request arguments dictionary with an additional key, __peloton_args__ with the request arguments list. args[0] is the channel on which to fire the event. args[1] is the exchange """ payload = request.args payload['__peloton_args'] = args[2:] self.kernel.dispatcher.fireEvent(args[0], args[1], **payload) request.write("OK") request.finish() def returnFavicon(self, request): request.setHeader('Content-Type','image/x-icon') thisDir = os.path.split(__file__)[0] iconPath = "%s/favicon.ico" % thisDir fsize = os.stat(iconPath)[6] request.setHeader('Content-Length',fsize) res = open(iconPath, 'rb') FileTransfer(res, fsize, request) def deferredResponse(self, resp, target, callbackName, mimeType, request): # str ensures not unicode which is not liked by # twisted.web resp = str(resp) if target == 'json' and callbackName: resp = "%s(%s)" % (callbackName, resp) request.setHeader('Content-Type', mimeType) request.setHeader('Content-Length', len(resp)) request.write(resp) request.finish() def deferredError(self, err, format, request): err = "ERROR: (%s) %s" % (err.parents[-1], err.getErrorMessage()) request.setHeader('Content-Type', 'text/plain') request.setHeader('Content-Length', len(err)) request.write(err) request.finish() def deliverStaticContent(self, resourceRoot, requestPath, request): """Read and deliver the static data content directly. """ resourcePath = os.path.realpath('%s/%s' % (resourceRoot, '/'.join(requestPath))) resourcePath = resourcePath.replace('//','/') # resourceRoot = resourceRoot.replace('//','/') # os.path.realpath expands softlinks. If we did not do this for # resource root it may not match resourcePath. realResourceRoot = os.path.realpath(resourceRoot) if not resourcePath.startswith(realResourceRoot): request.setResponseCode(404) self.kernel.logger.debug("Relative path (%s|%s|%s) in request points outside of resource root" % (requestPath,resourcePath, resourceRoot)) request.write("Relative path points outside resource root") request.finish() return if not os.path.isfile(resourcePath): request.setResponseCode(404) self.kernel.logger.debug("Request for non-existent static content") request.write("Static content unavailable.") request.finish() return suffix = resourcePath[resourcePath.rfind('.'):] if suffix in binaryFileMimeTypes.keys(): openMode = 'rb' request.setHeader('Content-Type', binaryFileMimeTypes[suffix]) elif suffix in plainFileMimeTypes.keys(): openMode = 'rt' request.setHeader('Content-Type', plainFileMimeTypes[suffix]) else: openMode = 'rt' request.setHeader('Content-Type', 'text/html') try: res = open(resourcePath, openMode) fsize = os.stat(resourcePath)[6] FileTransfer(res, fsize, request) except Exception, ex: request.setResponseCode(404) request.write("Could not read resource %s: %s" % (resourcePath, str(ex))) self.kernel.logger.debug("Could not read static resource %s: %s" % (resourcePath, str(ex))) request.finish() def _stopped(self, x): """ Handler called when reactor has stopped listening to this protocol's port.""" pass def stop(self): """ Close down this adapter. """ if self.connection: d = self.connection.stopListening() d.addCallback(self._stopped)
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/adapters/http.py", "copies": "1", "size": "9813", "license": "bsd-3-clause", "hash": -4940887955729227000, "line_mean": 40.0585774059, "line_max": 150, "alpha_frac": 0.598389891, "autogenerated": false, "ratio": 4.257266811279827, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5355656702279826, "avg_score": null, "num_lines": null }
# $Id: rfb.py 47 2008-05-27 02:10:00Z jon.oberheide $ # -*- coding: utf-8 -*- """Remote Framebuffer Protocol.""" from __future__ import absolute_import from . import dpkt # Remote Framebuffer Protocol # http://www.realvnc.com/docs/rfbproto.pdf # Client to Server Messages CLIENT_SET_PIXEL_FORMAT = 0 CLIENT_SET_ENCODINGS = 2 CLIENT_FRAMEBUFFER_UPDATE_REQUEST = 3 CLIENT_KEY_EVENT = 4 CLIENT_POINTER_EVENT = 5 CLIENT_CUT_TEXT = 6 # Server to Client Messages SERVER_FRAMEBUFFER_UPDATE = 0 SERVER_SET_COLOUR_MAP_ENTRIES = 1 SERVER_BELL = 2 SERVER_CUT_TEXT = 3 class RFB(dpkt.Packet): """Remote Framebuffer Protocol. TODO: Longer class information.... Attributes: __hdr__: Header fields of RADIUS. TODO. """ __hdr__ = ( ('type', 'B', 0), ) class SetPixelFormat(dpkt.Packet): __hdr__ = ( ('pad', '3s', ''), ('pixel_fmt', '16s', '') ) class SetEncodings(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('num_encodings', 'H', 0) ) class FramebufferUpdateRequest(dpkt.Packet): __hdr__ = ( ('incremental', 'B', 0), ('x_position', 'H', 0), ('y_position', 'H', 0), ('width', 'H', 0), ('height', 'H', 0) ) class KeyEvent(dpkt.Packet): __hdr__ = ( ('down_flag', 'B', 0), ('pad', '2s', ''), ('key', 'I', 0) ) class PointerEvent(dpkt.Packet): __hdr__ = ( ('button_mask', 'B', 0), ('x_position', 'H', 0), ('y_position', 'H', 0) ) class FramebufferUpdate(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('num_rects', 'H', 0) ) class SetColourMapEntries(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('first_colour', 'H', 0), ('num_colours', 'H', 0) ) class CutText(dpkt.Packet): __hdr__ = ( ('pad', '3s', ''), ('length', 'I', 0) )
{ "repo_name": "smutt/dpkt", "path": "dpkt/rfb.py", "copies": "3", "size": "1924", "license": "bsd-3-clause", "hash": -4312186176761077000, "line_mean": 18.24, "line_max": 53, "alpha_frac": 0.5088357588, "autogenerated": false, "ratio": 3.0251572327044025, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5033992991504402, "avg_score": null, "num_lines": null }
# $Id: rfb.py 47 2008-05-27 02:10:00Z jon.oberheide $ # -*- coding: utf-8 -*- """Remote Framebuffer Protocol.""" import dpkt # Remote Framebuffer Protocol # http://www.realvnc.com/docs/rfbproto.pdf # Client to Server Messages CLIENT_SET_PIXEL_FORMAT = 0 CLIENT_SET_ENCODINGS = 2 CLIENT_FRAMEBUFFER_UPDATE_REQUEST = 3 CLIENT_KEY_EVENT = 4 CLIENT_POINTER_EVENT = 5 CLIENT_CUT_TEXT = 6 # Server to Client Messages SERVER_FRAMEBUFFER_UPDATE = 0 SERVER_SET_COLOUR_MAP_ENTRIES = 1 SERVER_BELL = 2 SERVER_CUT_TEXT = 3 class RFB(dpkt.Packet): __hdr__ = ( ('type', 'B', 0), ) class SetPixelFormat(dpkt.Packet): __hdr__ = ( ('pad', '3s', ''), ('pixel_fmt', '16s', '') ) class SetEncodings(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('num_encodings', 'H', 0) ) class FramebufferUpdateRequest(dpkt.Packet): __hdr__ = ( ('incremental', 'B', 0), ('x_position', 'H', 0), ('y_position', 'H', 0), ('width', 'H', 0), ('height', 'H', 0) ) class KeyEvent(dpkt.Packet): __hdr__ = ( ('down_flag', 'B', 0), ('pad', '2s', ''), ('key', 'I', 0) ) class PointerEvent(dpkt.Packet): __hdr__ = ( ('button_mask', 'B', 0), ('x_position', 'H', 0), ('y_position', 'H', 0) ) class FramebufferUpdate(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('num_rects', 'H', 0) ) class SetColourMapEntries(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('first_colour', 'H', 0), ('num_colours', 'H', 0) ) class CutText(dpkt.Packet): __hdr__ = ( ('pad', '3s', ''), ('length', 'I', 0) )
{ "repo_name": "yangbh/dpkt", "path": "dpkt/rfb.py", "copies": "6", "size": "1716", "license": "bsd-3-clause", "hash": -8595211902806908000, "line_mean": 18.0666666667, "line_max": 53, "alpha_frac": 0.4994172494, "autogenerated": false, "ratio": 2.9084745762711863, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6407891825671186, "avg_score": null, "num_lines": null }
# $Id: rfb.py 47 2008-05-27 02:10:00Z jon.oberheide $ """Remote Framebuffer Protocol.""" import dpkt # Remote Framebuffer Protocol # http://www.realvnc.com/docs/rfbproto.pdf # Client to Server Messages CLIENT_SET_PIXEL_FORMAT = 0 CLIENT_SET_ENCODINGS = 2 CLIENT_FRAMEBUFFER_UPDATE_REQUEST = 3 CLIENT_KEY_EVENT = 4 CLIENT_POINTER_EVENT = 5 CLIENT_CUT_TEXT = 6 # Server to Client Messages SERVER_FRAMEBUFFER_UPDATE = 0 SERVER_SET_COLOUR_MAP_ENTRIES = 1 SERVER_BELL = 2 SERVER_CUT_TEXT = 3 class RFB(dpkt.Packet): __hdr__ = ( ('type', 'B', 0), ) class SetPixelFormat(dpkt.Packet): __hdr__ = ( ('pad', '3s', ''), ('pixel_fmt', '16s', '') ) class SetEncodings(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('num_encodings', 'H', 0) ) class FramebufferUpdateRequest(dpkt.Packet): __hdr__ = ( ('incremental', 'B', 0), ('x_position', 'H', 0), ('y_position', 'H', 0), ('width', 'H', 0), ('height', 'H', 0) ) class KeyEvent(dpkt.Packet): __hdr__ = ( ('down_flag', 'B', 0), ('pad', '2s', ''), ('key', 'I', 0) ) class PointerEvent(dpkt.Packet): __hdr__ = ( ('button_mask', 'B', 0), ('x_position', 'H', 0), ('y_position', 'H', 0) ) class FramebufferUpdate(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('num_rects', 'H', 0) ) class SetColourMapEntries(dpkt.Packet): __hdr__ = ( ('pad', '1s', ''), ('first_colour', 'H', 0), ('num_colours', 'H', 0) ) class CutText(dpkt.Packet): __hdr__ = ( ('pad', '3s', ''), ('length', 'I', 0) )
{ "repo_name": "dproc/trex_odp_porting_integration", "path": "scripts/external_libs/dpkt-1.8.6/dpkt/rfb.py", "copies": "32", "size": "1843", "license": "apache-2.0", "hash": -7750087256625411000, "line_mean": 21.7530864198, "line_max": 53, "alpha_frac": 0.459576777, "autogenerated": false, "ratio": 3.1184433164128595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" Parse a WHOIS research dump and write out (just) the RPKI-relevant fields in myrpki-format CSV syntax. Unfortunately, unlike the ARIN and APNIC databases, the RIPE database doesn't really have any useful concept of an organizational handle. More precisely, while it has handles out the wazoo, none of them are useful as a reliable grouping mechanism for tracking which set of resources are held by a particular organization. So, instead of being able to track all of an organization's resources with a single handle as we can in the ARIN and APNIC databases, the best we can do with the RIPE database is to track individual resources, each with its own resource handle. Well, for prefixes -- ASN entries behave more like in the ARIN and APNIC databases. Feh. NB: The input data for this script is publicly available via FTP, but you'll have to fetch the data from RIPE yourself, and be sure to see the terms and conditions referenced by the data file header comments. """ import gzip from rpki.csv_utils import csv_writer class Handle(dict): want_tags = () want_status = ("ASSIGNED", "ASSIGNEDPA", "ASSIGNEDPI") debug = False def set(self, tag, val): if tag in self.want_tags: self[tag] = "".join(val.split(" ")) def check(self): for tag in self.want_tags: if not tag in self: return False if self.debug: self.log() return True def __repr__(self): return "<%s %s>" % (self.__class__.__name__, " ".join("%s:%s" % (tag, self.get(tag, "?")) for tag in self.want_tags)) def log(self): print repr(self) def finish(self, ctx): self.check() class aut_num(Handle): want_tags = ("aut-num", "mnt-by") # "as-name" def set(self, tag, val): if tag == "aut-num" and val.startswith("AS"): val = val[2:] Handle.set(self, tag, val) def finish(self, ctx): if self.check(): ctx.asns.writerow((self["mnt-by"], self["aut-num"])) class inetnum(Handle): want_tags = ("inetnum", "netname", "status") # "mnt-by" def finish(self, ctx): if self.check() and self["status"] in self.want_status: ctx.prefixes.writerow((self["netname"], self["inetnum"])) class inet6num(Handle): want_tags = ("inet6num", "netname", "status") # "mnt-by" def finish(self, ctx): if self.check() and self["status"] in self.want_status: ctx.prefixes.writerow((self["netname"], self["inet6num"])) class main(object): types = dict((x.want_tags[0], x) for x in (aut_num, inetnum, inet6num)) def finish_statement(self, done): if self.statement: tag, sep, val = self.statement.partition(":") assert sep, "Couldn't find separator in %r" % self.statement tag = tag.strip().lower() val = val.strip().upper() if self.cur is None: self.cur = self.types[tag]() if tag in self.types else False if self.cur is not False: self.cur.set(tag, val) if done and self.cur: self.cur.finish(self) self.cur = None filenames = ("ripe.db.aut-num.gz", "ripe.db.inet6num.gz", "ripe.db.inetnum.gz") def __init__(self): self.asns = csv_writer("asns.csv") self.prefixes = csv_writer("prefixes.csv") for fn in self.filenames: f = gzip.open(fn) self.statement = "" self.cur = None for line in f: line = line.expandtabs().partition("#")[0].rstrip("\n") if line and not line[0].isalpha(): self.statement += line[1:] if line[0] == "+" else line else: self.finish_statement(not line) self.statement = line self.finish_statement(True) f.close() self.asns.close() self.prefixes.close() main()
{ "repo_name": "farrokhi/dotfiles", "path": "bin/ripe-to-csv.py", "copies": "1", "size": "4542", "license": "bsd-2-clause", "hash": -6763835724299402000, "line_mean": 31.9130434783, "line_max": 81, "alpha_frac": 0.6583003082, "autogenerated": false, "ratio": 3.4804597701149427, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46387600783149424, "avg_score": null, "num_lines": null }
# $Id: rip.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Routing Information Protocol.""" from __future__ import print_function from __future__ import absolute_import from . import dpkt # RIP v2 - RFC 2453 # http://tools.ietf.org/html/rfc2453 REQUEST = 1 RESPONSE = 2 class RIP(dpkt.Packet): """Routing Information Protocol. TODO: Longer class information.... Attributes: __hdr__: Header fields of RIP. TODO. """ __hdr__ = ( ('cmd', 'B', REQUEST), ('v', 'B', 2), ('rsvd', 'H', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) l = [] self.auth = None while self.data: rte = RTE(self.data[:20]) if rte.family == 0xFFFF: self.auth = Auth(self.data[:20]) else: l.append(rte) self.data = self.data[20:] self.data = self.rtes = l def __len__(self): n = self.__hdr_len__ if self.auth: n += len(self.auth) n += sum(map(len, self.rtes)) return n def __bytes__(self): auth = b'' if self.auth: auth = bytes(self.auth) return self.pack_hdr() + auth + b''.join(map(bytes, self.rtes)) class RTE(dpkt.Packet): __hdr__ = ( ('family', 'H', 2), ('route_tag', 'H', 0), ('addr', 'I', 0), ('subnet', 'I', 0), ('next_hop', 'I', 0), ('metric', 'I', 1) ) class Auth(dpkt.Packet): __hdr__ = ( ('rsvd', 'H', 0xFFFF), ('type', 'H', 2), ('auth', '16s', 0) ) __s = b'\x02\x02\x00\x00\x00\x02\x00\x00\x01\x02\x03\x00\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x00\xc0\xa8\x01\x08\xff\xff\xff\xfc\x00\x00\x00\x00\x00\x00\x00\x01' def test_rtp_pack(): r = RIP(__s) assert (__s == bytes(r)) def test_rtp_unpack(): r = RIP(__s) assert (r.auth is None) assert (len(r.rtes) == 2) rte = r.rtes[1] assert (rte.family == 2) assert (rte.route_tag == 0) assert (rte.metric == 1) if __name__ == '__main__': test_rtp_pack() test_rtp_unpack() print('Tests Successful...')
{ "repo_name": "smutt/dpkt", "path": "dpkt/rip.py", "copies": "3", "size": "2208", "license": "bsd-3-clause", "hash": 3979859437658804000, "line_mean": 21.08, "line_max": 185, "alpha_frac": 0.495923913, "autogenerated": false, "ratio": 2.816326530612245, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48122504436122443, "avg_score": null, "num_lines": null }
# $Id: rip.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Routing Information Protocol.""" import dpkt # RIP v2 - RFC 2453 # http://tools.ietf.org/html/rfc2453 REQUEST = 1 RESPONSE = 2 class RIP(dpkt.Packet): __hdr__ = ( ('cmd', 'B', REQUEST), ('v', 'B', 2), ('rsvd', 'H', 0) ) def unpack(self, buf): dpkt.Packet.unpack(self, buf) l = [] self.auth = None while self.data: rte = RTE(self.data[:20]) if rte.family == 0xFFFF: self.auth = Auth(self.data[:20]) else: l.append(rte) self.data = self.data[20:] self.data = self.rtes = l def __len__(self): len = self.__hdr_len__ if self.auth: len += len(self.auth) len += sum(map(len, self.rtes)) return len def __str__(self): auth = '' if self.auth: auth = str(self.auth) return self.pack_hdr() + auth + ''.join(map(str, self.rtes)) class RTE(dpkt.Packet): __hdr__ = ( ('family', 'H', 2), ('route_tag', 'H', 0), ('addr', 'I', 0), ('subnet', 'I', 0), ('next_hop', 'I', 0), ('metric', 'I', 1) ) class Auth(dpkt.Packet): __hdr__ = ( ('rsvd', 'H', 0xFFFF), ('type', 'H', 2), ('auth', '16s', 0) ) __s = '\x02\x02\x00\x00\x00\x02\x00\x00\x01\x02\x03\x00\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x00\xc0\xa8\x01\x08\xff\xff\xff\xfc\x00\x00\x00\x00\x00\x00\x00\x01' def test_rtp_pack(): r = RIP(__s) assert (__s == str(r)) def test_rtp_unpack(): r = RIP(__s) assert (r.auth is None) assert (len(r.rtes) == 2) rte = r.rtes[1] assert (rte.family == 2) assert (rte.route_tag == 0) assert (rte.metric == 1) if __name__ == '__main__': test_rtp_pack() test_rtp_unpack() print 'Tests Successful...'
{ "repo_name": "hexcap/dpkt", "path": "dpkt/rip.py", "copies": "6", "size": "1963", "license": "bsd-3-clause", "hash": 5640214970032284000, "line_mean": 21.0674157303, "line_max": 184, "alpha_frac": 0.4803871625, "autogenerated": false, "ratio": 2.700137551581843, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0011722487257101247, "num_lines": 89 }
""" This module defines standard interpreted text role functions, a registry for interpreted text roles, and an API for adding to and retrieving from the registry. The interface for interpreted role functions is as follows:: def role_fn(name, rawtext, text, lineno, inliner, options={}, content=[]): code... # Set function attributes for customization: role_fn.options = ... role_fn.content = ... Parameters: - ``name`` is the local name of the interpreted text role, the role name actually used in the document. - ``rawtext`` is a string containing the entire interpreted text construct. Return it as a ``problematic`` node linked to a system message if there is a problem. - ``text`` is the interpreted text content, with backslash escapes converted to nulls (``\x00``). - ``lineno`` is the line number where the interpreted text beings. - ``inliner`` is the Inliner object that called the role function. It defines the following useful attributes: ``reporter``, ``problematic``, ``memo``, ``parent``, ``document``. - ``options``: A dictionary of directive options for customization, to be interpreted by the role function. Used for additional attributes for the generated elements and other functionality. - ``content``: A list of strings, the directive content for customization ("role" directive). To be interpreted by the role function. Function attributes for customization, interpreted by the "role" directive: - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in the `directives` module. All role functions implicitly support the "class" option, unless disabled with an explicit ``{'class': None}``. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Note that unlike directives, the "arguments" function attribute is not supported for role customization. Directive arguments are handled by the "role" directive itself. Interpreted role functions return a tuple of two values: - A list of nodes which will be inserted into the document tree at the point where the interpreted role was encountered (can be an empty list). - A list of system messages, which will be inserted into the document tree immediately after the end of the current inline block (can also be empty). """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.parsers.rst import directives from docutils.parsers.rst.languages import en as _fallback_language_module DEFAULT_INTERPRETED_ROLE = 'title-reference' """ The canonical name of the default interpreted role. This role is used when no role is specified for a piece of interpreted text. """ _role_registry = {} """Mapping of canonical role names to role functions. Language-dependent role names are defined in the ``language`` subpackage.""" _roles = {} """Mapping of local or language-dependent interpreted text role names to role functions.""" def role(role_name, language_module, lineno, reporter): """ Locate and return a role function from its language-dependent name, along with a list of system messages. If the role is not found in the current language, check English. Return a 2-tuple: role function (``None`` if the named role cannot be found) and a list of system messages. """ normname = role_name.lower() messages = [] msg_text = [] if normname in _roles: return _roles[normname], messages if role_name: canonicalname = None try: canonicalname = language_module.roles[normname] except AttributeError, error: msg_text.append('Problem retrieving role entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No role entry for "%s" in module "%s".' % (role_name, language_module.__name__)) else: canonicalname = DEFAULT_INTERPRETED_ROLE # If we didn't find it, try English as a fallback. if not canonicalname: try: canonicalname = _fallback_language_module.roles[normname] msg_text.append('Using English fallback for role "%s".' % role_name) except KeyError: msg_text.append('Trying "%s" as canonical role name.' % role_name) # The canonical name should be an English name, but just in case: canonicalname = normname # Collect any messages that we generated. if msg_text: message = reporter.info('\n'.join(msg_text), line=lineno) messages.append(message) # Look the role up in the registry, and return it. if canonicalname in _role_registry: role_fn = _role_registry[canonicalname] register_local_role(normname, role_fn) return role_fn, messages else: return None, messages # Error message will be generated by caller. def register_canonical_role(name, role_fn): """ Register an interpreted text role by its canonical name. :Parameters: - `name`: The canonical name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _role_registry[name] = role_fn def register_local_role(name, role_fn): """ Register an interpreted text role by its local or language-dependent name. :Parameters: - `name`: The local or language-dependent name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _roles[name] = role_fn def set_implicit_options(role_fn): """ Add customization options to role functions, unless explicitly set or disabled. """ if not hasattr(role_fn, 'options') or role_fn.options is None: role_fn.options = {'class': directives.class_option} elif 'class' not in role_fn.options: role_fn.options['class'] = directives.class_option def register_generic_role(canonical_name, node_class): """For roles which simply wrap a given `node_class` around the text.""" role = GenericRole(canonical_name, node_class) register_canonical_role(canonical_name, role) class GenericRole: """ Generic interpreted text role, where the interpreted text is simply wrapped with the provided node class. """ def __init__(self, role_name, node_class): self.name = role_name self.node_class = node_class def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) return [self.node_class(rawtext, utils.unescape(text), **options)], [] class CustomRole: """ Wrapper for custom interpreted text roles. """ def __init__(self, role_name, base_role, options={}, content=[]): self.name = role_name self.base_role = base_role self.options = None if hasattr(base_role, 'options'): self.options = base_role.options self.content = None if hasattr(base_role, 'content'): self.content = base_role.content self.supplied_options = options self.supplied_content = content def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): opts = self.supplied_options.copy() opts.update(options) cont = list(self.supplied_content) if cont and content: cont += '\n' cont.extend(content) return self.base_role(role, rawtext, text, lineno, inliner, options=opts, content=cont) def generic_custom_role(role, rawtext, text, lineno, inliner, options={}, content=[]): """""" # Once nested inline markup is implemented, this and other methods should # recursively call inliner.nested_parse(). set_classes(options) return [nodes.inline(rawtext, utils.unescape(text), **options)], [] generic_custom_role.options = {'class': directives.class_option} ###################################################################### # Define and register the standard roles: ###################################################################### register_generic_role('abbreviation', nodes.abbreviation) register_generic_role('acronym', nodes.acronym) register_generic_role('emphasis', nodes.emphasis) register_generic_role('literal', nodes.literal) register_generic_role('strong', nodes.strong) register_generic_role('subscript', nodes.subscript) register_generic_role('superscript', nodes.superscript) register_generic_role('title-reference', nodes.title_reference) def pep_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: pepnum = int(text) if pepnum < 0 or pepnum > 9999: raise ValueError except ValueError: msg = inliner.reporter.error( 'PEP number must be a number from 0 to 9999; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.pep_reference; so this is correct: ref = (inliner.document.settings.pep_base_url + inliner.document.settings.pep_file_url_template % pepnum) set_classes(options) return [nodes.reference(rawtext, 'PEP ' + utils.unescape(text), refuri=ref, **options)], [] register_canonical_role('pep-reference', pep_reference_role) def rfc_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: rfcnum = int(text) if rfcnum <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'RFC number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.rfc_reference, so this is correct: ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum set_classes(options) node = nodes.reference(rawtext, 'RFC ' + utils.unescape(text), refuri=ref, **options) return [node], [] register_canonical_role('rfc-reference', rfc_reference_role) def raw_role(role, rawtext, text, lineno, inliner, options={}, content=[]): if 'format' not in options: msg = inliner.reporter.error( 'No format (Writer name) is associated with this role: "%s".\n' 'The "raw" role cannot be used directly.\n' 'Instead, use the "role" directive to create a new role with ' 'an associated format.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] set_classes(options) node = nodes.raw(rawtext, utils.unescape(text, 1), **options) return [node], [] raw_role.options = {'format': directives.unchanged} register_canonical_role('raw', raw_role) ###################################################################### # Register roles that are currently unimplemented. ###################################################################### def unimplemented_role(role, rawtext, text, lineno, inliner, attributes={}): msg = inliner.reporter.error( 'Interpreted text role "%s" not implemented.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] register_canonical_role('index', unimplemented_role) register_canonical_role('named-reference', unimplemented_role) register_canonical_role('anonymous-reference', unimplemented_role) register_canonical_role('uri-reference', unimplemented_role) register_canonical_role('footnote-reference', unimplemented_role) register_canonical_role('citation-reference', unimplemented_role) register_canonical_role('substitution-reference', unimplemented_role) register_canonical_role('target', unimplemented_role) # This should remain unimplemented, for testing purposes: register_canonical_role('restructuredtext-unimplemented-role', unimplemented_role) def set_classes(options): """ Auxiliary function to set options['classes'] and delete options['class']. """ if 'class' in options: assert 'classes' not in options options['classes'] = options['class'] del options['class']
{ "repo_name": "spreeker/democracygame", "path": "external_apps/docutils-snapshot/build/lib/docutils/parsers/rst/roles.py", "copies": "2", "size": "12978", "license": "bsd-3-clause", "hash": 4114028113499681300, "line_mean": 36.5086705202, "line_max": 79, "alpha_frac": 0.6514100786, "autogenerated": false, "ratio": 4.141033822590938, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007453351735356289, "num_lines": 346 }
""" This module defines standard interpreted text role functions, a registry for interpreted text roles, and an API for adding to and retrieving from the registry. The interface for interpreted role functions is as follows:: def role_fn(name, rawtext, text, lineno, inliner, options={}, content=[]): code... # Set function attributes for customization: role_fn.options = ... role_fn.content = ... Parameters: - ``name`` is the local name of the interpreted text role, the role name actually used in the document. - ``rawtext`` is a string containing the entire interpreted text construct. Return it as a ``problematic`` node linked to a system message if there is a problem. - ``text`` is the interpreted text content, with backslash escapes converted to nulls (``\x00``). - ``lineno`` is the line number where the interpreted text beings. - ``inliner`` is the Inliner object that called the role function. It defines the following useful attributes: ``reporter``, ``problematic``, ``memo``, ``parent``, ``document``. - ``options``: A dictionary of directive options for customization, to be interpreted by the role function. Used for additional attributes for the generated elements and other functionality. - ``content``: A list of strings, the directive content for customization ("role" directive). To be interpreted by the role function. Function attributes for customization, interpreted by the "role" directive: - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in the `directives` module. All role functions implicitly support the "class" option, unless disabled with an explicit ``{'class': None}``. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Note that unlike directives, the "arguments" function attribute is not supported for role customization. Directive arguments are handled by the "role" directive itself. Interpreted role functions return a tuple of two values: - A list of nodes which will be inserted into the document tree at the point where the interpreted role was encountered (can be an empty list). - A list of system messages, which will be inserted into the document tree immediately after the end of the current inline block (can also be empty). """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.parsers.rst import directives from docutils.parsers.rst.languages import en as _fallback_language_module DEFAULT_INTERPRETED_ROLE = 'title-reference' """ The canonical name of the default interpreted role. This role is used when no role is specified for a piece of interpreted text. """ _role_registry = {} """Mapping of canonical role names to role functions. Language-dependent role names are defined in the ``language`` subpackage.""" _roles = {} """Mapping of local or language-dependent interpreted text role names to role functions.""" def role(role_name, language_module, lineno, reporter): """ Locate and return a role function from its language-dependent name, along with a list of system messages. If the role is not found in the current language, check English. Return a 2-tuple: role function (``None`` if the named role cannot be found) and a list of system messages. """ normname = role_name.lower() messages = [] msg_text = [] if normname in _roles: return _roles[normname], messages if role_name: canonicalname = None try: canonicalname = language_module.roles[normname] except AttributeError, error: msg_text.append('Problem retrieving role entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No role entry for "%s" in module "%s".' % (role_name, language_module.__name__)) else: canonicalname = DEFAULT_INTERPRETED_ROLE # If we didn't find it, try English as a fallback. if not canonicalname: try: canonicalname = _fallback_language_module.roles[normname] msg_text.append('Using English fallback for role "%s".' % role_name) except KeyError: msg_text.append('Trying "%s" as canonical role name.' % role_name) # The canonical name should be an English name, but just in case: canonicalname = normname # Collect any messages that we generated. if msg_text: message = reporter.info('\n'.join(msg_text), line=lineno) messages.append(message) # Look the role up in the registry, and return it. if canonicalname in _role_registry: role_fn = _role_registry[canonicalname] register_local_role(normname, role_fn) return role_fn, messages else: return None, messages # Error message will be generated by caller. def register_canonical_role(name, role_fn): """ Register an interpreted text role by its canonical name. :Parameters: - `name`: The canonical name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _role_registry[name] = role_fn def register_local_role(name, role_fn): """ Register an interpreted text role by its local or language-dependent name. :Parameters: - `name`: The local or language-dependent name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _roles[name] = role_fn def set_implicit_options(role_fn): """ Add customization options to role functions, unless explicitly set or disabled. """ if not hasattr(role_fn, 'options') or role_fn.options is None: role_fn.options = {'class': directives.class_option} elif 'class' not in role_fn.options: role_fn.options['class'] = directives.class_option def register_generic_role(canonical_name, node_class): """For roles which simply wrap a given `node_class` around the text.""" role = GenericRole(canonical_name, node_class) register_canonical_role(canonical_name, role) class GenericRole: """ Generic interpreted text role, where the interpreted text is simply wrapped with the provided node class. """ def __init__(self, role_name, node_class): self.name = role_name self.node_class = node_class def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) return [self.node_class(rawtext, utils.unescape(text), **options)], [] class CustomRole: """ Wrapper for custom interpreted text roles. """ def __init__(self, role_name, base_role, options={}, content=[]): self.name = role_name self.base_role = base_role self.options = None if hasattr(base_role, 'options'): self.options = base_role.options self.content = None if hasattr(base_role, 'content'): self.content = base_role.content self.supplied_options = options self.supplied_content = content def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): opts = self.supplied_options.copy() opts.update(options) cont = list(self.supplied_content) if cont and content: cont += '\n' cont.extend(content) return self.base_role(role, rawtext, text, lineno, inliner, options=opts, content=cont) def generic_custom_role(role, rawtext, text, lineno, inliner, options={}, content=[]): """""" # Once nested inline markup is implemented, this and other methods should # recursively call inliner.nested_parse(). set_classes(options) return [nodes.inline(rawtext, utils.unescape(text), **options)], [] generic_custom_role.options = {'class': directives.class_option} ###################################################################### # Define and register the standard roles: ###################################################################### register_generic_role('abbreviation', nodes.abbreviation) register_generic_role('acronym', nodes.acronym) register_generic_role('emphasis', nodes.emphasis) register_generic_role('literal', nodes.literal) register_generic_role('strong', nodes.strong) register_generic_role('subscript', nodes.subscript) register_generic_role('superscript', nodes.superscript) register_generic_role('title-reference', nodes.title_reference) def pep_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: pepnum = int(text) if pepnum < 0 or pepnum > 9999: raise ValueError except ValueError: msg = inliner.reporter.error( 'PEP number must be a number from 0 to 9999; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.pep_reference; so this is correct: ref = (inliner.document.settings.pep_base_url + inliner.document.settings.pep_file_url_template % pepnum) set_classes(options) return [nodes.reference(rawtext, 'PEP ' + utils.unescape(text), refuri=ref, **options)], [] register_canonical_role('pep-reference', pep_reference_role) def rfc_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: rfcnum = int(text) if rfcnum <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'RFC number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.rfc_reference, so this is correct: ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum set_classes(options) node = nodes.reference(rawtext, 'RFC ' + utils.unescape(text), refuri=ref, **options) return [node], [] register_canonical_role('rfc-reference', rfc_reference_role) def raw_role(role, rawtext, text, lineno, inliner, options={}, content=[]): if not inliner.document.settings.raw_enabled: msg = inliner.reporter.warning('raw (and derived) roles disabled') prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] if 'format' not in options: msg = inliner.reporter.error( 'No format (Writer name) is associated with this role: "%s".\n' 'The "raw" role cannot be used directly.\n' 'Instead, use the "role" directive to create a new role with ' 'an associated format.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] set_classes(options) node = nodes.raw(rawtext, utils.unescape(text, 1), **options) return [node], [] raw_role.options = {'format': directives.unchanged} register_canonical_role('raw', raw_role) ###################################################################### # Register roles that are currently unimplemented. ###################################################################### def unimplemented_role(role, rawtext, text, lineno, inliner, attributes={}): msg = inliner.reporter.error( 'Interpreted text role "%s" not implemented.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] register_canonical_role('index', unimplemented_role) register_canonical_role('named-reference', unimplemented_role) register_canonical_role('anonymous-reference', unimplemented_role) register_canonical_role('uri-reference', unimplemented_role) register_canonical_role('footnote-reference', unimplemented_role) register_canonical_role('citation-reference', unimplemented_role) register_canonical_role('substitution-reference', unimplemented_role) register_canonical_role('target', unimplemented_role) # This should remain unimplemented, for testing purposes: register_canonical_role('restructuredtext-unimplemented-role', unimplemented_role) def set_classes(options): """ Auxiliary function to set options['classes'] and delete options['class']. """ if 'class' in options: assert 'classes' not in options options['classes'] = options['class'] del options['class']
{ "repo_name": "rimbalinux/MSISDNArea", "path": "docutils/parsers/rst/roles.py", "copies": "2", "size": "13537", "license": "bsd-3-clause", "hash": -6054533389781365000, "line_mean": 36.6771428571, "line_max": 79, "alpha_frac": 0.6347048829, "autogenerated": false, "ratio": 4.185837971552258, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007228292610375811, "num_lines": 350 }
""" This module defines standard interpreted text role functions, a registry for interpreted text roles, and an API for adding to and retrieving from the registry. The interface for interpreted role functions is as follows:: def role_fn(name, rawtext, text, lineno, inliner, options={}, content=[]): code... # Set function attributes for customization: role_fn.options = ... role_fn.content = ... Parameters: - ``name`` is the local name of the interpreted text role, the role name actually used in the document. - ``rawtext`` is a string containing the entire interpreted text construct. Return it as a ``problematic`` node linked to a system message if there is a problem. - ``text`` is the interpreted text content, with backslash escapes converted to nulls (``\x00``). - ``lineno`` is the line number where the interpreted text beings. - ``inliner`` is the Inliner object that called the role function. It defines the following useful attributes: ``reporter``, ``problematic``, ``memo``, ``parent``, ``document``. - ``options``: A dictionary of directive options for customization, to be interpreted by the role function. Used for additional attributes for the generated elements and other functionality. - ``content``: A list of strings, the directive content for customization ("role" directive). To be interpreted by the role function. Function attributes for customization, interpreted by the "role" directive: - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in the `directives` module. All role functions implicitly support the "class" option, unless disabled with an explicit ``{'class': None}``. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Note that unlike directives, the "arguments" function attribute is not supported for role customization. Directive arguments are handled by the "role" directive itself. Interpreted role functions return a tuple of two values: - A list of nodes which will be inserted into the document tree at the point where the interpreted role was encountered (can be an empty list). - A list of system messages, which will be inserted into the document tree immediately after the end of the current inline block (can also be empty). """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.parsers.rst import directives from docutils.parsers.rst.languages import en as _fallback_language_module DEFAULT_INTERPRETED_ROLE = 'title-reference' """ The canonical name of the default interpreted role. This role is used when no role is specified for a piece of interpreted text. """ _role_registry = {} """Mapping of canonical role names to role functions. Language-dependent role names are defined in the ``language`` subpackage.""" _roles = {} """Mapping of local or language-dependent interpreted text role names to role functions.""" def role(role_name, language_module, lineno, reporter): """ Locate and return a role function from its language-dependent name, along with a list of system messages. If the role is not found in the current language, check English. Return a 2-tuple: role function (``None`` if the named role cannot be found) and a list of system messages. """ normname = role_name.lower() messages = [] msg_text = [] if normname in _roles: return _roles[normname], messages if role_name: canonicalname = None try: canonicalname = language_module.roles[normname] except AttributeError, error: msg_text.append('Problem retrieving role entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No role entry for "%s" in module "%s".' % (role_name, language_module.__name__)) else: canonicalname = DEFAULT_INTERPRETED_ROLE # If we didn't find it, try English as a fallback. if not canonicalname: try: canonicalname = _fallback_language_module.roles[normname] msg_text.append('Using English fallback for role "%s".' % role_name) except KeyError: msg_text.append('Trying "%s" as canonical role name.' % role_name) # The canonical name should be an English name, but just in case: canonicalname = normname # Collect any messages that we generated. if msg_text: message = reporter.info('\n'.join(msg_text), line=lineno) messages.append(message) # Look the role up in the registry, and return it. if canonicalname in _role_registry: role_fn = _role_registry[canonicalname] register_local_role(normname, role_fn) return role_fn, messages else: return None, messages # Error message will be generated by caller. def register_canonical_role(name, role_fn): """ Register an interpreted text role by its canonical name. :Parameters: - `name`: The canonical name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _role_registry[name] = role_fn def register_local_role(name, role_fn): """ Register an interpreted text role by its local or language-dependent name. :Parameters: - `name`: The local or language-dependent name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _roles[name] = role_fn def set_implicit_options(role_fn): """ Add customization options to role functions, unless explicitly set or disabled. """ if not hasattr(role_fn, 'options') or role_fn.options is None: role_fn.options = {'class': directives.class_option} elif 'class' not in role_fn.options: role_fn.options['class'] = directives.class_option def register_generic_role(canonical_name, node_class): """For roles which simply wrap a given `node_class` around the text.""" role = GenericRole(canonical_name, node_class) register_canonical_role(canonical_name, role) class GenericRole: """ Generic interpreted text role, where the interpreted text is simply wrapped with the provided node class. """ def __init__(self, role_name, node_class): self.name = role_name self.node_class = node_class def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) return [self.node_class(rawtext, utils.unescape(text), **options)], [] class CustomRole: """ Wrapper for custom interpreted text roles. """ def __init__(self, role_name, base_role, options={}, content=[]): self.name = role_name self.base_role = base_role self.options = None if hasattr(base_role, 'options'): self.options = base_role.options self.content = None if hasattr(base_role, 'content'): self.content = base_role.content self.supplied_options = options self.supplied_content = content def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): opts = self.supplied_options.copy() opts.update(options) cont = list(self.supplied_content) if cont and content: cont += '\n' cont.extend(content) return self.base_role(role, rawtext, text, lineno, inliner, options=opts, content=cont) def generic_custom_role(role, rawtext, text, lineno, inliner, options={}, content=[]): """""" # Once nested inline markup is implemented, this and other methods should # recursively call inliner.nested_parse(). set_classes(options) return [nodes.inline(rawtext, utils.unescape(text), **options)], [] generic_custom_role.options = {'class': directives.class_option} ###################################################################### # Define and register the standard roles: ###################################################################### register_generic_role('abbreviation', nodes.abbreviation) register_generic_role('acronym', nodes.acronym) register_generic_role('emphasis', nodes.emphasis) register_generic_role('literal', nodes.literal) register_generic_role('strong', nodes.strong) register_generic_role('subscript', nodes.subscript) register_generic_role('superscript', nodes.superscript) register_generic_role('title-reference', nodes.title_reference) def pep_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: pepnum = int(text) if pepnum < 0 or pepnum > 9999: raise ValueError except ValueError: msg = inliner.reporter.error( 'PEP number must be a number from 0 to 9999; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.pep_reference; so this is correct: ref = (inliner.document.settings.pep_base_url + inliner.document.settings.pep_file_url_template % pepnum) set_classes(options) return [nodes.reference(rawtext, 'PEP ' + utils.unescape(text), refuri=ref, **options)], [] register_canonical_role('pep-reference', pep_reference_role) def rfc_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: rfcnum = int(text) if rfcnum <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'RFC number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.rfc_reference, so this is correct: ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum set_classes(options) node = nodes.reference(rawtext, 'RFC ' + utils.unescape(text), refuri=ref, **options) return [node], [] register_canonical_role('rfc-reference', rfc_reference_role) def raw_role(role, rawtext, text, lineno, inliner, options={}, content=[]): if not inliner.document.settings.raw_enabled: msg = inliner.reporter.warning('raw (and derived) roles disabled') prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] if 'format' not in options: msg = inliner.reporter.error( 'No format (Writer name) is associated with this role: "%s".\n' 'The "raw" role cannot be used directly.\n' 'Instead, use the "role" directive to create a new role with ' 'an associated format.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] set_classes(options) node = nodes.raw(rawtext, utils.unescape(text, 1), **options) return [node], [] raw_role.options = {'format': directives.unchanged} register_canonical_role('raw', raw_role) def math_role(role, rawtext, text, lineno, inliner, options={}, content=[]): i = rawtext.find('`') text = rawtext.split('`')[1] node = nodes.math(rawtext, text) return [node], [] register_canonical_role('math', math_role) ###################################################################### # Register roles that are currently unimplemented. ###################################################################### def unimplemented_role(role, rawtext, text, lineno, inliner, attributes={}): msg = inliner.reporter.error( 'Interpreted text role "%s" not implemented.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] register_canonical_role('index', unimplemented_role) register_canonical_role('named-reference', unimplemented_role) register_canonical_role('anonymous-reference', unimplemented_role) register_canonical_role('uri-reference', unimplemented_role) register_canonical_role('footnote-reference', unimplemented_role) register_canonical_role('citation-reference', unimplemented_role) register_canonical_role('substitution-reference', unimplemented_role) register_canonical_role('target', unimplemented_role) # This should remain unimplemented, for testing purposes: register_canonical_role('restructuredtext-unimplemented-role', unimplemented_role) def set_classes(options): """ Auxiliary function to set options['classes'] and delete options['class']. """ if 'class' in options: assert 'classes' not in options options['classes'] = options['class'] del options['class']
{ "repo_name": "paaschpa/badcomputering", "path": "docutils/parsers/rst/roles.py", "copies": "6", "size": "13426", "license": "bsd-3-clause", "hash": 3878989175920361000, "line_mean": 36.6078431373, "line_max": 79, "alpha_frac": 0.6510502011, "autogenerated": false, "ratio": 4.105810397553517, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008602683752684648, "num_lines": 357 }