code
stringlengths
1
1.72M
language
stringclasses
1 value
from meshUtils import * #end
Python
import os import sys from api import mel from maya.cmds import * from filesystem import Path, removeDupes, BreakException, getArgDefault from vectors import Vector import maya.cmds as cmd import filesystem import rigUtils import triggered import colours import meshUtils import profileDecorators from apiExtensions import asMObject, MObject from common import printErrorStr SPACE_WORLD = rigUtils.SPACE_WORLD SPACE_LOCAL = rigUtils.SPACE_LOCAL SPACE_OBJECT = rigUtils.SPACE_OBJECT Axis = rigUtils.Axis CONTROL_DIRECTORY = None if CONTROL_DIRECTORY is None: #try to determine the directory that contains the control macros dirsToSearch = [ Path( __file__ ).up() ] + sys.path + os.environ[ 'MAYA_SCRIPT_PATH' ].split( os.pathsep ) dirsToSearch = map( Path, dirsToSearch ) dirsToSearch = removeDupes( dirsToSearch ) for dirToSearch in dirsToSearch: if not dirToSearch.isDir(): continue foundControlDir = False for f in dirToSearch.files( recursive=True ): if f.hasExtension( 'shape' ): if f.name().startswith( 'control' ): CONTROL_DIRECTORY = f.up() foundControlDir = True break if foundControlDir: break if CONTROL_DIRECTORY is None: printErrorStr( "Cannot determine the directory that contains the *.control files - please open '%s' and set the CONTROL_DIRECTORY variable appropriately" % Path( __file__ ) ) AX_X, AX_Y, AX_Z, AX_X_NEG, AX_Y_NEG, AX_Z_NEG = map( Axis, range( 6 ) ) DEFAULT_AXIS = AX_X AXIS_ROTATIONS = { AX_X: (0, 0, -90), AX_Y: (0, 0, 0), AX_Z: (90, 0, 0), AX_X_NEG: (0, 0, 90), AX_Y_NEG: (180, 0, 0), AX_Z_NEG: (-90, 0, 0) } class ShapeDesc(object): ''' store shape preferences about a control ''' NULL_SHAPE = None SKIN = 1 DEFAULT_TYPE = 'cube' def __init__( self, surfaceType=DEFAULT_TYPE, curveType=None, axis=DEFAULT_AXIS, expand=0.04, joints=None ): ''' surfaceType must be a valid control preset name - defaults to cube if none is specified curveType must also be a valid control preset name and defaults to the surface name if not specified ''' self.surfaceType = surfaceType self.curveType = curveType if curveType is None: self.curveType = surfaceType self.axis = axis self.expand = expand if joints is None: self.joints = [] else: self.joints = joints if isinstance( joints, (tuple, list) ) else [ joints ] def __repr__( self ): return repr( self.surfaceType or self.curveType ) __str__ = __repr__ DEFAULT_SHAPE_DESC = ShapeDesc() SHAPE_NULL = ShapeDesc( ShapeDesc.NULL_SHAPE, ShapeDesc.NULL_SHAPE ) Shape_Skin = lambda joints=None, **kw: ShapeDesc( ShapeDesc.SKIN, ShapeDesc.NULL_SHAPE, joints=joints, **kw ) DEFAULT_SKIN_EXTRACTION_TOLERANCE = getArgDefault( meshUtils.extractMeshForJoints, 'tolerance' ) class PlaceDesc(object): WORLD = None PLACE_OBJ = 0 ALIGN_OBJ = 1 PIVOT_OBJ = 2 Place = 0 Align = 1 Pivot = 2 def __init__( self, placeAtObj=WORLD, alignToObj=PLACE_OBJ, snapPivotToObj=PLACE_OBJ ): #now convert the inputs to actual objects, if they're not already self._placeData = placeAtObj, alignToObj, snapPivotToObj self.place = self.getObj( self.Place ) self.align = self.getObj( self.Align ) self.pivot = self.getObj( self.Pivot ) def getObj( self, item ): p = self._placeData[ item ] if isinstance( p, MObject ): return p if p == self.PLACE_OBJ: p = self._placeData[ 0 ] elif p == self.ALIGN_OBJ: p = self._placeData[ 1 ] elif p == self.PIVOT_OBJ: p = self._placeData[ 2 ] if isinstance( p, basestring ): return p if isinstance( p, int ): return self.WORLD if p is None: return self.WORLD return p def getLocation( self, obj ): if obj is None: return Vector() return xform( obj, q=True, ws=True, rp=True ) placePos = property( lambda self: self.getLocation( self.place ) ) alignPos = property( lambda self: self.getLocation( self.align ) ) pivotPos = property( lambda self: self.getLocation( self.pivot ) ) DEFAULT_PLACE_DESC = PlaceDesc() class PivotModeDesc(object): BASE, MID, TOP = 0, 1, 2 ColourDesc = colours.Colour DEFAULT_COLOUR = ColourDesc( 'orange' ) def _performOnAttr( obj, attrName, metaName, metaState ): childAttrs = attributeQuery( attrName, n=obj, listChildren=True ) or [] if childAttrs: for a in childAttrs: setAttr( '%s.%s' % (obj, a), **{ metaName: metaState } ) else: setAttr( '%s.%s' % (obj, attrName), **{ metaName: metaState } ) NORMAL = False, True HIDE = None, False, False LOCK_HIDE = True, False, False NO_KEY = False, False, True LOCK_SHOW = True, True, True def attrState( objs, attrNames, lock=None, keyable=None, show=None ): if not isinstance( objs, (list, tuple) ): objs = [ objs ] objs = map( str, objs ) if not isinstance( attrNames, (list, tuple) ): attrNames = [ attrNames ] for obj in objs: for attrName in attrNames: #showInChannelBox( False ) doesn't work if setKeyable is true - which is kinda dumb... if show is not None: if not show: _performOnAttr( obj, attrName, 'keyable', False ) keyable = None _performOnAttr( obj, attrName, 'keyable', show ) if lock is not None: _performOnAttr( obj, attrName, 'lock', lock ) if keyable is not None: _performOnAttr( obj, attrName, 'keyable', keyable ) def getJointSizeAndCentre( joints, threshold=0.65, space=SPACE_OBJECT ): ''' minor modification to the getJointSize function in rigging.utils - uses the child of the joint[ 0 ] (if any exist) to determine the size of the joint in the axis aiming toward ''' centre = Vector.Zero( 3 ) if not isinstance( joints, (list, tuple) ): joints = [ joints ] joints = [ str( j ) for j in joints if j is not None ] if not joints: return Vector( (1, 1, 1) ) size, centre = rigUtils.getJointSizeAndCentre( joints, threshold, space ) if size.within( Vector.Zero( 3 ), 1e-2 ): while threshold > 1e-2: threshold *= 0.9 size, centre = rigUtils.getJointSizeAndCentre( joints, threshold ) if size.within( Vector.Zero( 3 ), 1e-2 ): size = Vector( (1, 1, 1) ) children = listRelatives( joints[ 0 ], pa=True, type='transform' ) if children: childPos = Vector( [ 0.0, 0.0, 0.0 ] ) childPosMag = childPos.get_magnitude() for child in children: curChildPos = Vector( xform( child, q=True, ws=True, rp=True ) ) - Vector( xform( joints[ 0 ], q=True, ws=True, rp=True ) ) curChildPosMag = curChildPos.get_magnitude() if curChildPosMag > childPosMag: childPos = curChildPos childPosMag = curChildPosMag axis = rigUtils.getObjectAxisInDirection( joints[ 0 ], childPos, DEFAULT_AXIS ) axisValue = getAttr( '%s.t%s' % (children[ 0 ], axis.asCleanName()) ) if space == SPACE_WORLD: axis = Axis.FromVector( childPos ) size[ axis % 3 ] = abs( axisValue ) centre[ axis % 3 ] = axisValue / 2.0 return size, centre getJointSizeAndCenter = getJointSizeAndCentre #for spelling n00bs def getJointSize( joints, threshold=0.65, space=SPACE_OBJECT ): return getJointSizeAndCentre( joints, threshold, space )[ 0 ] def getAutoOffsetAmount( placeObject, joints=None, axis=AX_Z, threshold=0.65 ): ''' returns a value reflecting the distance from the placeObject to the edge of the bounding box containing the verts skinned to the joints in the joints list the axis controls what edge of the bounding box is used if joints is None, [placeObject] is used ''' if joints is None: joints = [ placeObject ] else: joints = removeDupes( [ placeObject ] + joints ) #make sure the placeObject is the first item in the joints list, otherwise the bounds won't be transformed to the correct space #get the bounds of the geo skinned to the hand and use it to determine default placement of the slider control bounds = rigUtils.getJointBounds( joints ) offsetAmount = abs( bounds[ axis.isNegative() ][ axis % 3 ] ) #print bounds[ 0 ].x, bounds[ 0 ].y, bounds[ 0 ].z, bounds[ 1 ].x, bounds[ 1 ].y, bounds[ 1 ].z return offsetAmount AUTO_SIZE = None DEFAULT_HIDE_ATTRS = ( 'scale', 'visibility' ) def buildControl( name, placementDesc=DEFAULT_PLACE_DESC, pivotModeDesc=PivotModeDesc.MID, shapeDesc=DEFAULT_SHAPE_DESC, colour=DEFAULT_COLOUR, constrain=True, oriented=True, offset=Vector( (0, 0, 0) ), offsetSpace=SPACE_OBJECT, size=Vector( (1, 1, 1) ), scale=1.0, autoScale=False, parent=None, qss=None, asJoint=False, freeze=True, lockAttrs=( 'scale', ), hideAttrs=DEFAULT_HIDE_ATTRS, niceName=None, displayLayer=None ): ''' this rather verbosely called function deals with creating control objects in a variety of ways. the following args take "struct" like instances of the classes defined above, so look to them for more detail on defining those options displayLayer (int) will create layers (if doesn't exist) and add control shape to that layer. layer None or zero doesn't create. ''' select( cl=True ) #sanity checks... if not isinstance( placementDesc, PlaceDesc ): if isinstance( placementDesc, (list, tuple) ): placementDesc = PlaceDesc( *placementDesc ) else: placementDesc = PlaceDesc( placementDesc ) if not isinstance( shapeDesc, ShapeDesc ): if isinstance( shapeDesc, (list, tuple) ): shapeDesc = ShapeDesc( *shapeDesc ) else: shapeDesc = ShapeDesc( shapeDesc ) offset = Vector( offset ) #if we've been given a parent, cast it to be an MObject so that if its name path changes (for example if #parent='aNode' and we create a control called 'aNode' then the parent's name path will change to '|aNode' - yay!) if parent: parent = asMObject( parent ) #unpack placement objects place, align, pivot = placementDesc.place, placementDesc.align, placementDesc.pivot if shapeDesc.surfaceType == ShapeDesc.SKIN: shapeDesc.curveType = ShapeDesc.NULL_SHAPE #never build curve shapes if the surface type is skin if shapeDesc.joints is None: shapeDesc.joints = [ str( place ) ] shapeDesc.expand *= scale #determine auto scale/size - if nessecary if autoScale: _scale = list( getJointSize( [ place ] + (shapeDesc.joints or []) ) ) _scale = sorted( _scale )[ -1 ] if abs( _scale ) < 1e-2: print 'AUTO SCALE FAILED', _scale, name, place _scale = scale scale = _scale if size is AUTO_SIZE: tmpKw = {} if oriented else { 'space': SPACE_WORLD } size = getJointSize( [ place ] + (shapeDesc.joints or []), **tmpKw ) for n, v in enumerate( size ): if abs( v ) < 1e-2: size[ n ] = scale scale = 1.0 #if we're doing a SKIN shape, ensure there is actually geometry skinned to the joints, otherwise bail on the skin and change to the default type if shapeDesc.surfaceType == ShapeDesc.SKIN: try: #loop over all joints and see if there is geo skinned to it for j in shapeDesc.joints: verts = meshUtils.jointVerts( j, tolerance=DEFAULT_SKIN_EXTRACTION_TOLERANCE ) #if so throw a breakException to bail out of the loop if verts: raise BreakException #if we get this far that means none of the joints have geo skinned to them - so set the surface and curve types to their default values shapeDesc.surfaceType = shapeDesc.curveType = ShapeDesc.DEFAULT_TYPE print 'WARNING - surface type was set to SKIN, but no geometry is skinned to the joints: %s' % shapeDesc.joints except BreakException: pass #build the curve shapes first if shapeDesc.curveType != ShapeDesc.NULL_SHAPE \ and shapeDesc.curveType != ShapeDesc.SKIN: curveShapeFile = getFileForShapeName( shapeDesc.curveType ) assert curveShapeFile is not None, "cannot find shape %s" % shapeDesc.curveType createCmd = ''.join( curveShapeFile.read() ) mel.eval( createCmd ) else: select( group( em=True ) ) sel = ls( sl=True ) obj = asMObject( sel[ 0 ] ) #now to deal with the surface - if its different from the curve, then build it if shapeDesc.surfaceType != shapeDesc.curveType \ and shapeDesc.surfaceType != ShapeDesc.NULL_SHAPE \ and shapeDesc.surfaceType != ShapeDesc.SKIN: #if the typesurface is different from the typecurve, then first delete all existing surface shapes under the control shapesTemp = listRelatives( obj, s=True, pa=True ) for s in shapesTemp: if nodeType( s ) == "nurbsSurface": delete( s ) #now build the temporary control surfaceShapeFile = getFileForShapeName( shapeDesc.surfaceType ) assert surfaceShapeFile is not None, "cannot find shape %s" % shapeDesc.surfaceType createCmd = ''.join( surfaceShapeFile.read() ) mel.eval( createCmd ) #and parent its surface shape nodes to the actual control, and then delete it tempSel = ls( sl=True ) shapesTemp = listRelatives( tempSel[0], s=True, pa=True ) or [] for s in shapesTemp: if nodeType(s) == "nurbsSurface": cmd.parent( s, obj, add=True, s=True ) delete( tempSel[ 0 ] ) select( sel ) #if the joint flag is true, parent the object shapes under a joint instead of a transform node if asJoint: select( cl=True ) j = joint() for s in listRelatives( obj, s=True, pa=True ) or []: cmd.parent( s, j, add=True, s=True ) setAttr( '%s.radius' % j, keyable=False ) setAttr( '%s.radius' % j, cb=False ) delete( obj ) obj = asMObject( j ) setAttr( '%s.s' % obj, scale, scale, scale ) #rename the object - if no name has been given, call it "control". if there is a node with the name already, get maya to uniquify it if not name: name = 'control' if objExists( name ): name = '%s#' % name rename( obj, name ) #move the pivot - if needed makeIdentity( obj, a=1, s=1 ) shapeStrs = getShapeStrs( obj ) if pivotModeDesc == PivotModeDesc.TOP: for s in shapeStrs: move( 0, -scale/2.0, 0, s, r=True ) elif pivotModeDesc == PivotModeDesc.BASE: for s in shapeStrs: move( 0, scale/2.0, 0, s, r=True ) #rotate it accordingly rot = AXIS_ROTATIONS[ shapeDesc.axis ] rotate( rot[0], rot[1], rot[2], obj, os=True ) makeIdentity( obj, a=1, r=1 ) #if the user wants the control oriented, create the orientation group and parent the control grp = obj if oriented: grp = group( em=True, n="%s_space#" % obj ) cmd.parent( obj, grp ) attrState( grp, ['s', 'v'], *LOCK_HIDE ) if align is not None: delete( parentConstraint( align, grp ) ) #place and align if place: delete( pointConstraint( place, grp ) ) if align: delete( orientConstraint( align, grp ) ) else: rotate( 0, 0, 0, grp, a=True, ws=True ) #do the size scaling... if shapeDesc.surfaceType != ShapeDesc.SKIN: for s in getShapeStrs( obj ): cmd.scale( size[0], size[1], size[2], s ) #if the parent exists - parent the new control to the given parent if parent is not None: grp = cmd.parent( grp, parent )[0] #do offset for s in getShapeStrs( obj ): mkw = { 'r': True } if offsetSpace == SPACE_OBJECT: mkw[ 'os' ] = True elif offsetSpace == SPACE_LOCAL: mkw[ 'ls' ] = True elif offsetSpace == SPACE_WORLD: mkw[ 'ws' ] = True if offset: move( offset[0], offset[1], offset[2], s, **mkw ) if freeze: makeIdentity( obj, a=1, r=1 ) makeIdentity( obj, a=1, t=1 ) #always freeze translations #delete shape data that we don't want if shapeDesc.curveType is None: for s in listRelatives( obj, s=True, pa=True ) or []: if nodeType(s) == "nurbsCurve": delete(s) if shapeDesc.surfaceType is None: for s in listRelatives( obj, s=True, pa=True ) or []: if nodeType(s) == "nurbsSurface": delete(s) #now snap the pivot to alignpivot object if it exists if pivot is not None and objExists( pivot ): p = placementDesc.pivotPos move( p[0], p[1], p[2], '%s.rp' % obj, '%s.sp' % obj, a=True, ws=True, rpr=True ) #constrain the target object to this control? if constrain: #check to see if the transform is constrained already - if so, bail. buildControl doesn't do multi constraints if not listConnections( pivot, d=0, type='constraint' ): if place: parentConstraint( obj, pivot, mo=True ) setItemRigControl( pivot, obj ) #if the user has specified skin geometry as the representation type, then build the geo #NOTE: this really needs to happen after ALL the placement has happened otherwise the extracted #will be offset from the surface its supposed to be representing if shapeDesc.surfaceType == ShapeDesc.SKIN: #extract the surface geometry geo = meshUtils.extractMeshForJoints( shapeDesc.joints, expand=shapeDesc.expand ) #if the geo is None, use the default control representation instead writeTrigger = True if geo is None: writeTrigger = False curveShapeFile = getFileForShapeName( ShapeDesc.DEFAULT_TYPE ) createCmd = ''.join( curveShapeFile.read() ) mel.eval( createCmd ) geo = ls( sl=True )[ 0 ] geo = cmd.parent( geo, obj )[0] makeIdentity( geo, a=True, s=True, r=True, t=True ) cmd.parent( listRelatives( geo, s=True, pa=True ), obj, add=True, s=True ) delete( geo ) #when selected, turn the mesh display off, and only highlight edges if writeTrigger: triggered.Trigger.CreateTrigger( str( obj ), cmdStr="for( $s in `listRelatives -s -pa #` ) setAttr ( $s +\".displayEdges\" ) 2;" ) #build a shader for the control if colour is not None: colours.setObjShader( obj, colours.getShader( colour, True ) ) #add to a selection set if desired if qss is not None: sets( obj, add=qss ) #hide and lock attributes attrState( obj, lockAttrs, lock=True ) attrState( obj, hideAttrs, show=False ) if niceName: setNiceName( obj, niceName ) # display layer if displayLayer and not int( displayLayer ) <= 0 : layerName = 'ctrl_%d' % int( displayLayer ) allLayers = ls( type='displayLayer' ) layer = '' if layerName in allLayers: layer = layerName else: layer = createDisplayLayer( n=layerName, number=1, empty=True ) setAttr( '%s.color' % layer, 24 + int( displayLayer ) ) for s in listRelatives( obj, s=True, pa=True ) or []: connectAttr( '%s.drawInfo.visibility' % layer, '%s.v' % s ) connectAttr( '%s.drawInfo.displayType' % layer, '%s.overrideDisplayType' % s ) return obj def buildControlAt( name, *a, **kw ): kw[ 'constrain' ] = False return buildControl( name, *a, **kw ) def buildNullControl( name, *a, **kw ): kw[ 'shapeDesc' ] = SHAPE_NULL kw[ 'oriented' ] = False kw[ 'constrain' ] = False return buildControl( name, *a, **kw ) def buildAlignedNull( alignTo, name=None, *a, **kw ): if name is None: name = 'alignedNull' return buildControl( name, alignTo, shapeDesc=SHAPE_NULL, constrain=False, oriented=False, freeze=False, *a, **kw ) def setItemRigControl( item, control ): ''' used to associate an item within a skeleton part with a rig control ''' attrPath = '%s._skeletonPartRigControl' % item if not objExists( attrPath ): addAttr( item, ln='_skeletonPartRigControl', at='message' ) connectAttr( '%s.message' % control, attrPath, f=True ) return True def getItemRigControl( item ): ''' returns the control associated with the item within a skeleton part, or None if there is no control driving the item ''' attrPath = '%s._skeletonPartRigControl' % item if objExists( attrPath ): cons = listConnections( attrPath, d=False ) if cons: return cons[ 0 ] return None def getNiceName( obj ): attrPath = '%s._NICE_NAME' % obj if objExists( attrPath ): return getAttr( attrPath ) return None def setNiceName( obj, niceName ): attrPath = '%s._NICE_NAME' % obj if not objExists( attrPath ): addAttr( obj, ln='_NICE_NAME', dt='string' ) setAttr( attrPath, niceName, type='string' ) SHAPE_TO_COMPONENT_NAME = { 'nurbsSurface': 'cv', 'nurbsCurve': 'cv', 'mesh': 'vtx' } def getShapeStrs( obj ): ''' returns a list of names to refer to all components for all shapes under the given object ''' global SHAPE_TO_COMPONENT_NAME geo = [] shapes = listRelatives( obj, s=True, pa=True ) or [] for s in shapes: nType = str( nodeType( s ) ) cName = SHAPE_TO_COMPONENT_NAME[ nType ] geo.append( "%s.%s[*]" % (s, cName) ) return geo def getControlShapeFiles(): dir = CONTROL_DIRECTORY if isinstance( dir, basestring ): dir = Path( dir ) if not isinstance( dir, Path ) or not dir.exists(): dir = Path( __file__ ).up() shapes = [] if dir.exists(): shapes = [ f for f in dir.files() if f.hasExtension( 'shape' ) ] if not shapes: searchPaths = map( Path, sys.path ) searchPaths += map( Path, os.environ.get( 'MAYA_SCRIPT_PATH', '' ).split( ';' ) ) searchPaths = removeDupes( searchPaths ) for d in searchPaths: try: shapes += [ f for f in d.files() if f.hasExtension( 'shape' ) ] except WindowsError: continue return shapes CONTROL_SHAPE_FILES = getControlShapeFiles() CONTROL_SHAPE_DICT = {} for f in CONTROL_SHAPE_FILES: CONTROL_SHAPE_DICT[ f.name().split( '.' )[ -1 ].lower() ] = f def getFileForShapeName( shapeName ): theFile = CONTROL_SHAPE_DICT.get( shapeName.lower(), None ) return theFile @profileDecorators.d_profile def speedTest(): import time start = time.clock() for n in range( 100 ): buildControl( 'apples' ) print 'time taken %0.3f' % (time.clock()-start) #end
Python
from baseMelUI import * from apiExtensions import iterParents from melUtils import mel, melecho import maya.cmds as cmd import mappingEditor import mappingUtils import xferAnim import animLib __author__ = 'mel@macaronikazoo.com' class XferAnimForm(MelVSingleStretchLayout): def __init__( self, parent ): MelVSingleStretchLayout.__init__( self, parent ) self.sortBySrcs = True #otherwise it sorts by tgts when doing traces self._clipPreset = None self.UI_mapping = mappingEditor.MappingForm( self ) self.UI_options = MelFrameLayout( self, l="xfer options", labelVisible=True, collapsable=False, collapse=False, h=115, borderStyle='etchedIn' ) #need to specify the height for 2011 coz its ghey! hLayout = MelHLayout( self.UI_options ) colLayout = MelColumnLayout( hLayout ) self.UI_radios = MelRadioCollection() self.RAD_dupe = self.UI_radios.createButton( colLayout, l="duplicate nodes", align='left', sl=True, cc=self.on_update ) self.RAD_copy = self.UI_radios.createButton( colLayout, l="copy/paste keys", align='left', cc=self.on_update ) self.RAD_trace = self.UI_radios.createButton( colLayout, l="trace objects", align='left', cc=self.on_update ) colLayout = MelColumnLayout( hLayout ) self.UI_check1 = MelCheckBox( colLayout, l="instance animation" ) self.UI_check2 = MelCheckBox( colLayout, l="match rotate order", v=1 ) self.UI_check3 = MelCheckBox( colLayout, l="", vis=0, v=0 ) self.UI_check4 = MelCheckBox( colLayout, l="", vis=0, v=1 ) hLayout.layout() hLayout = MelHLayout( self.UI_options ) self.UI_keysOnly = MelCheckBox( hLayout, l="keys only", v=0, cc=self.on_update ) self.UI_withinRange = MelCheckBox( hLayout, l="within range:", v=0, cc=self.on_update ) MelLabel( hLayout, l="start ->" ) self.UI_start = MelTextField( hLayout, en=0, tx='!' ) cmd.popupMenu( p=self.UI_start, b=3, pmc=self.buildTimeMenu ) MelLabel( hLayout, l="end ->" ) self.UI_end = MelTextField( hLayout, en=0, tx='!' ) cmd.popupMenu( p=self.UI_end, b=3, pmc=self.buildTimeMenu ) UI_button = cmd.button( self, l='Xfer Animation', c=self.on_xfer ) self.setStretchWidget( self.UI_mapping ) self.layout() self.on_update() #set initial state def isTraceMode( self, theMode ): m = self.UI_radios.getSelected() return theMode.endswith( '|'+ m ) def setMapping( self, mapping ): self.UI_mapping.setMapping( mapping ) def setClipPreset( self, clipPreset, mapping=None ): self._clipPreset = clipPreset #setup the file specific UI fileDict = clipPreset.unpickle() add = False delta = fileDict[ animLib.kEXPORT_DICT_CLIP_TYPE ] == animLib.kDELTA world = fileDict.get( animLib.kEXPORT_DICT_WORLDSPACE, False ) nocreate = False #populate the source objects from the file self.UI_mapping.replaceSrcItems( fileDict[ animLib.kEXPORT_DICT_OBJECTS ] ) self.UI_options( e=True, l="import options" ) cmd.radioButton( self.RAD_dupe, e=True, en=True, sl=True, l="absolute times" ) cmd.radioButton( self.RAD_copy, e=True, en=True, l="current time offset" ) cmd.radioButton( self.RAD_trace, e=True, en=False, vis=False, l="current time offset" ) cmd.checkBox( self.UI_check1, e=True, l="additive key values", vis=True, v=add ) cmd.checkBox( self.UI_check2, e=True, l="match rotate order", vis=True, v=0 ) cmd.checkBox( self.UI_check3, e=True, l="import as world space", vis=True, v=world ) cmd.checkBox( self.UI_check4, e=True, l="don't create new keys", vis=True, v=nocreate ) self.on_update() ### MENU BUILDERS ### def buildTimeMenu( self, parent, uiItem ): cmd.menu( parent, e=True, dai=True ) cmd.setParent( parent, m=True ) cmd.menuItem( l="! - use current range", c=lambda a: cmd.textField( uiItem, e=True, tx='!' ) ) cmd.menuItem( l=". - use current frame", c=lambda a: cmd.textField( uiItem, e=True, tx='.' ) ) cmd.menuItem( l="$ - use scene range", c=lambda a: cmd.textField( uiItem, e=True, tx='$' ) ) ### EVENT HANDLERS ### def on_update( self, *a ): sel = cmd.ls( sl=True, dep=True ) if not self._clipPreset is not None: if self.isTraceMode( self.RAD_dupe ): cmd.checkBox( self.UI_check1, e=True, en=True ) else: cmd.checkBox( self.UI_check1, e=True, en=False, v=0 ) if self.isTraceMode( self.RAD_trace ): cmd.checkBox( self.UI_keysOnly, e=True, en=True ) cmd.checkBox( self.UI_check2, e=True, v=0 ) cmd.checkBox( self.UI_check3, e=True, vis=1, v=1, l="process post-trace cmds" ) else: cmd.checkBox( self.UI_keysOnly, e=True, en=False, v=0 ) cmd.checkBox( self.UI_check3, e=True, vis=0, v=0 ) if cmd.checkBox( self.UI_keysOnly, q=True, v=True ): cmd.checkBox( self.UI_withinRange, e=True, en=1 ) else: cmd.checkBox( self.UI_withinRange, e=True, en=0, v=0 ) enableRange = self.isTraceMode( self.RAD_copy ) or self.isTraceMode( self.RAD_trace ) keysOnly = cmd.checkBox( self.UI_keysOnly, q=True, v=True ) withinRange = cmd.checkBox( self.UI_withinRange, q=True, v=True ) if enableRange and not keysOnly or withinRange: cmd.textField( self.UI_start, e=True, en=True ) cmd.textField( self.UI_end, e=True, en=True ) else: cmd.textField( self.UI_start, e=True, en=False ) cmd.textField( self.UI_end, e=True, en=False ) def on_xfer( self, *a ): mapping = mappingUtils.resolveMappingToScene( self.UI_mapping.getMapping() ) theSrcs = [] theTgts = [] #perform the hierarchy sort idx = 0 if self.sortBySrcs else 1 toSort = [ (len(list(iterParents( srcAndTgt[ idx ] ))), srcAndTgt) for srcAndTgt in mapping.iteritems() if cmd.objExists( srcAndTgt[ idx ] ) ] toSort.sort() for idx, (src, tgt) in toSort: theSrcs.append( src ) theTgts.append( tgt ) offset = '' isDupe = self.isTraceMode( self.RAD_dupe ) isCopy = self.isTraceMode( self.RAD_copy ) isTraced = self.isTraceMode( self.RAD_trace ) instance = cmd.checkBox( self.UI_check1, q=True, v=True ) traceKeys = cmd.checkBox( self.UI_keysOnly, q=True, v=True ) matchRo = cmd.checkBox( self.UI_check2, q=True, v=True ) startTime = cmd.textField( self.UI_start, q=True, tx=True ) endTime = cmd.textField( self.UI_end, q=True, tx=True ) world = processPostCmds = cmd.checkBox( self.UI_check3, q=True, v=True ) #this is also "process trace cmds" nocreate = cmd.checkBox( self.UI_check4, q=True, v=True ) if startTime.isdigit(): startTime = int( startTime ) else: if startTime == '!': startTime = cmd.playbackOptions( q=True, min=True ) elif startTime == '.': startTime = cmd.currentTime( q=True ) elif startTime == '$': startTime = cmd.playbackOptions( q=True, animationStartTime=True ) if endTime.isdigit(): endTime = int( endTime ) else: if endTime == '!': endTime = cmd.playbackOptions( q=True, max=True ) elif endTime == '.': endTime = cmd.currentTime( q=True ) elif endTime == '$': endTime = cmd.playbackOptions( q=True, animationEndTime=True ) withinRange = cmd.checkBox( self.UI_withinRange, q=True, v=True ) if withinRange: traceKeys = 2 if isCopy: offset = "*" if self._clipPreset is not None: #convert to mapping as expected by animLib... this is messy! animLibMapping = {} for src, tgts in mapping.iteritems(): animLibMapping[ src ] = tgts[ 0 ] self._clipPreset.asClip().apply( animLibMapping ) elif isDupe: melecho.zooXferBatch( "-mode 0 -instance %d -matchRo %d" % (instance, matchRo), theSrcs, theTgts ) elif isCopy: melecho.zooXferBatch( "-mode 1 -range %s %s -matchRo %d" % (startTime, endTime, matchRo), theSrcs, theTgts ) elif isTraced: xferAnim.trace( theSrcs, theTgts, traceKeys, matchRo, processPostCmds, True, startTime, endTime ) class XferAnimWindow(BaseMelWindow): WINDOW_NAME = 'xferAnim' WINDOW_TITLE = 'Xfer Anim' DEFAULT_SIZE = 350, 450 DEFAULT_MENU = 'Tools' def __init__( self, mapping=None, clipPreset=None ): BaseMelWindow.__init__( self ) self.editor = XferAnimForm( self ) if mapping is not None: self.editor.setMapping( mapping ) if clipPreset is not None: self.editor.setClipPreset( clipPreset ) self.show() #end
Python
import maya.mel from maya.cmds import cmd melEval = maya.mel.eval def pyArgToMelArg( arg ): #given a python arg, this method will attempt to convert it to a mel arg string if isinstance( arg, basestring ): return u'"%s"' % cmd.encodeString( arg ) #if the object is iterable then turn it into a mel array string elif hasattr( arg, '__iter__' ): return '{%s}' % ','.join( map( pyArgToMelArg, arg ) ) #either lower case bools or ints for mel please... elif isinstance( arg, bool ): return str( arg ).lower() #otherwise try converting the sucka to a string directly return unicode( arg ) class Mel( object ): ''' creates an easy to use interface to mel code as opposed to having string formatting operations all over the place in scripts that call mel functionality ''' def __init__( self, echo=False ): self.echo = echo def __getattr__( self, attr ): if attr.startswith( '__' ) and attr.endswith( '__' ): return self.__dict__[attr] #construct the mel cmd execution method echo = self.echo def melExecutor( *args ): strArgs = map( pyArgToMelArg, args ) cmdStr = '%s(%s);' % (attr, ','.join( strArgs )) if echo: print cmdStr try: retVal = melEval( cmdStr ) except RuntimeError: print 'cmdStr: %s' % cmdStr return return retVal melExecutor.__name__ = attr return melExecutor def source( self, script ): return melEval( 'source "%s";' % script ) def eval( self, cmdStr ): if self.echo: print cmdStr try: return melEval( cmdStr ) except RuntimeError: print 'ERROR :: trying to execute the cmd:' print cmdStr raise mel = Mel() melecho = Mel(echo=True) #end
Python
from baseSkeletonBuilder import * class ArbitraryChain(SkeletonPart): HAS_PARITY = False @classmethod def _build( cls, parent=None, partName='', jointCount=5, direction='-z', **kw ): if not partName: partName = cls.__name__ idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] partName = '%s%s' % (partName, idx) parent = getParent( parent ) dirMult = cls.ParityMultiplier( idx ) if cls.HAS_PARITY else 1 length = partScale lengthInc = dirMult * length / jointCount directionAxis = rigUtils.Axis.FromName( direction ) directionVector = directionAxis.asVector() * lengthInc directionVector = list( directionVector ) otherIdx = directionAxis.otherAxes()[ 1 ] parityStr = idx.asName() if cls.HAS_PARITY else '' allJoints = [] prevParent = parent half = jointCount / 2 for n in range( jointCount ): j = createJoint( '%s_%d%s' % (partName, n, parityStr) ) cmd.parent( j, prevParent, r=True ) moveVector = directionVector + [ j ] moveVector[ otherIdx ] = dirMult * n * lengthInc / jointCount / 5.0 move( moveVector[0], moveVector[1], moveVector[2], j, r=True, ws=True ) allJoints.append( j ) prevParent = j return allJoints def _align( self, _initialAlign=False ): parity = Parity( 0 ) if self.hasParity(): parity = self.getParity() num = len( self ) if num == 1: autoAlignItem( self[ 0 ], parity ) elif num == 2: for i in self.selfAndOrphans(): autoAlignItem( i, parity ) else: #in this case we want to find a plane that roughly fits the chain. #for the sake of simplicity take the first, last and some joint in #the middle and fit a plane to them, and use it's normal for the upAxis midJoint = self[ num / 2 ] defaultUpVector = rigUtils.getObjectBasisVectors( self[ 0 ] )[ BONE_OTHER_AXIS ] normal = getPlaneNormalForObjects( self.base, midJoint, self.end, defaultUpVector ) normal *= parity.asMultiplier() for n, i in enumerate( self[ :-1 ] ): alignAimAtItem( i, self[ n+1 ], parity, worldUpVector=normal ) autoAlignItem( self[ -1 ], parity, worldUpVector=normal ) #should we align the orphans? rigKwargs = self.getRigKwargs() if 'rigOrphans' in rigKwargs: if rigKwargs[ 'rigOrphans' ]: for i in self.getOrphanJoints(): autoAlignItem( i, parity, worldUpVector=normal ) # read just the rotations to be inline with the parent joint -- wish we didn't have to do this endPlacer = self.endPlacer if endPlacer: setAttr( '%s.r' % endPlacer, 0, 0, 0 ) def visualize( self ): scale = self.getBuildScale() / 10.0 midJoint = self[ len( self ) / 2 ] class ArbitraryParityChain(ArbitraryChain): HAS_PARITY = True #end
Python
from maya.OpenMaya import * from vectors import Vector, Matrix import sys import maya.cmds as cmd import time getAttr = cmd.getAttr setAttr = cmd.setAttr MObject.__MPlug__ = None def asMObject( otherMobject ): ''' tries to cast the given obj to an mobject - it can be string ''' if isinstance( otherMobject, basestring ): sel = MSelectionList() sel.add( otherMobject ) if '.' in otherMobject: plug = MPlug() sel.getPlug( 0, plug ) tmp = plug.asMObject() tmp.__MPlug__ = plug else: tmp = MObject() sel.getDependNode( 0, tmp ) return tmp if isinstance( otherMobject, (MObject, MObjectHandle) ): return otherMobject def asMPlug( otherMobject ): if '.' in otherMobject: sel = MSelectionList() sel.add( otherMobject ) plug = MPlug() sel.getPlug( 0, plug ) return plug def _asDependencyNode( self ): if not self.hasFn( MFn.kDependencyNode ): return None if self.__MDependencyNode__ is None: self.__MDependencyNode__ = dep = MFnDependencyNode( self ) return dep else: return self.__MDependencyNode__ MObject.__MDependencyNode__ = None MObject.dependencyNode = _asDependencyNode def _asDag( self ): if not self.hasFn( MFn.kDagNode ): return None if self.__MDagPath__ is None: self.__MDagPath__ = dag = MDagPath() MDagPath.getAPathTo( self, dag ) return dag else: return self.__MDagPath__ MObject.__MDagPath__ = None MObject.dagPath = _asDag def partialPathName( self ): ''' returns the partial name of the node ''' if self.isNull(): return unicode() if isinstance( self, MObjectHandle ): self = self.object() dagPath = self.dagPath() if dagPath is not None: return dagPath.partialPathName() #already a unicode instance if self.hasFn( MFn.kDependencyNode ): return MFnDependencyNode( self ).name() elif self.hasFn( MFn.kAttribute ): sel = MSelectionList() sel.add( self ) node = MObject() self.getDependNode( 0, node ) return unicode( MPlug( node, self ) ) return u'<instance of %s>' % self.__class__ def __repr( self ): return repr( self.partialPathName() ) MObject.__str__ = MObjectHandle.__str__ = partialPathName MObject.__repr__ = MObjectHandle.__repr__ = __repr MObject.__unicode__ = MObjectHandle.__unicode__ = partialPathName MObject.partialPathName = MObjectHandle.partialPathName = partialPathName MObject.this = None #stops __getattr__ from being called def isNotEqual( self, other ): return not self == other #override the default __eq__ operator on MObject. NOTE: because the original __eq__ method is cached above, #reloading this module can result in funkiness because the __eq__ gets cached on reload. the alternative is #to have an "originalMethods" script that never gets reloaded and stores original overridable methods MObject.__ne__ = isNotEqual def shortName( self ): return partialPathName( self ).split( '|' )[ -1 ] MObject.shortName = MObjectHandle.shortName = shortName def _hash( self ): return MObjectHandle( self ).hashCode() MObject.__hash__ = _hash def _hash( self ): return self.hashCode() MObjectHandle.__hash__ = _hash def cmpNodes( a, b ): ''' compares two nodes and returns whether they're equivalent or not - the compare is done on MObjects not strings so passing the fullname and a partial name to the same dag will still return True ''' if a is b: return True #make sure the objects are valid types... if b is None: return False if isinstance( a, basestring ): a = asMObject( a ) if isinstance( b, basestring ): b = asMObject( b ) if not isinstance( a, MObject ): return False if not isinstance( b, MObject ): return False return a == b def __eq( self, other ): if isinstance( other, basestring ): other = asMObject( other ) return MObjectOriginalEquivalenceMethod( self, other ) #check to see if __eq__ has been setup already - if it has, the sys._MObjectOriginalEquivalenceMethod attribute will exist if not hasattr( sys, '_MObjectOriginalEquivalenceMethod' ): sys._MObjectOriginalEquivalenceMethod = MObjectOriginalEquivalenceMethod = MObject.__eq__ #store on sys so that it doesn't get garbage collected when flush is called MObject.__eq__ = __eq else: MObjectOriginalEquivalenceMethod = sys._MObjectOriginalEquivalenceMethod MObject.__eq__ = __eq print "mobject __eq__ already setup!" #preGetAttr = MObject.__getattr__ def __getattr__( self, attr ): return MFnDependencyNode( self ).findPlug( attr ) #MObject.__getattr__ = __getattr__ #woah! this can really really slow maya down... MObject.getAttr = __getattr__ def iterAttrs( self, attrNamesToSkip=() ): ''' iterates over all MPlugs belonging to this assumed to be dependency node ''' depFn = MFnDependencyNode( self ) for n in range( depFn.attributeCount() ): mattr = depFn.attribute( n ) if mattr.isNull(): continue mPlug = MPlug( self, mattr ) mPlugName = mPlug.longName() skipAttr = False for skipName in attrNamesToSkip: if mPlugName == skipName: skipAttr = True elif mPlugName.startswith( skipName +'[' ) or mPlugName.startswith( skipName +'.' ): skipAttr = True if skipAttr: continue yield mPlug MObject.iterAttrs = iterAttrs def hasAttribute( self, attr ): return MFnDependencyNode( self ).hasAttribute( attr ) MObject.hasAttribute = hasAttribute def getParent( self ): ''' returns the parent of this node as an mobject ''' if self.hasFn( MFn.kDagNode ): dagPath = MDagPath() MDagPath.getAPathTo( self, dagPath ) dagNode = MFnDagNode( dagPath ).parent( 0 ) if dagNode.apiType() == MFn.kWorld: return None return dagNode def setParent( self, newParent, relative=False ): ''' sets the parent of this node - newParent can be either another mobject or a node name ''' dagMod = MDagModifier() dagMod.reparentNode( self, asMObject( newParent ) ) dagMod.doIt() #cmd.parent( str( self ), str( newParent ), r=relative ) MObject.getParent = getParent MObject.setParent = setParent def hasUniqueName( self ): return MFnDependencyNode( self ).hasUniqueName() MObject.hasUniqueName = hasUniqueName def _rename( self, newName ): ''' renames the node ''' return cmd.rename( self, newName ) MObject.rename = _rename def getShortName( self ): if not isinstance( self, basestring ): self = str( self ) return self.split( ':' )[ -1 ] MObject.shortName = getShortName def getObjectMatrix( self ): dag = self.dagPath() if dag is None: return None return dag.getObjectMatrix() MObject.getObjectMatrix = getObjectMatrix def getWorldMatrix( self ): dag = self.dagPath() if dag is None: return None return dag.getWorldMatrix() MObject.getWorldMatrix = getWorldMatrix def getWorldInverseMatrix( self ): dag = self.dagPath() if dag is None: return None return dag.getWorldInverseMatrix() MObject.getWorldInverseMatrix = getWorldInverseMatrix def getParentMatrix( self ): dag = self.dagPath() if dag is None: return None return dag.getParentMatrix() MObject.getParentMatrix = getParentMatrix def getParentInverseMatrix( self ): dag = self.dagPath() if dag is None: return None return dag.getParentInverseMatrix() MObject.getParentInverseMatrix = getParentInverseMatrix ### MDAGPATH CUSTOMIZATIONS ### MDagPath.__str__ = MDagPath.partialPathName MDagPath.__repr__ = MDagPath.partialPathName MDagPath.__unicode__ = MDagPath.partialPathName MDagPath.this = None def getObjectMatrix( self ): return MFnTransform( self ).transformation().asMatrix().asNice() MDagPath.getObjectMatrix = getObjectMatrix def getWorldMatrix( self ): return self.inclusiveMatrix().asNice() MDagPath.getWorldMatrix = getWorldMatrix def getWorldInverseMatrix( self ): return self.inclusiveMatrixInverse().asNice() MDagPath.getWorldInverseMatrix = getWorldInverseMatrix def getParentMatrix( self ): return self.exclusiveMatrix().asNice() MDagPath.getParentMatrix = getParentMatrix def getParentInverseMatrix( self ): return self.exclusiveMatrixInverse().asNice() MDagPath.getParentInverseMatrix = getParentInverseMatrix ### MPLUG CUSTOMIZATIONS ### def __unicode__( self ): return self.name().replace( '[-1]', '[0]' ) MPlug.__str__ = __unicode__ MPlug.__repr__ = __unicode__ MPlug.__unicode__ = __unicode__ #MPlug.this = None #stops __getattr__ from being called def __getattr__( self, attr ): ''' for getting child attributes ''' if self.numChildren(): return [ self.child(idx) for idx in range( self.numChildren() ) ] def __getitem__( self, idx ): ''' for getting indexed attributes ''' if self.isArray(): return self.elementByLogicalIndex( idx ) raise TypeError( "Attribute %s isn't indexable" % self ) #MPlug.__getattr__ = __getattr__ #MPlug.__getitem__ = __getitem__ MPlug.asMObject = MPlug.attribute def _set( self, value ): if isinstance( value, (list, tuple) ): setAttr( str(self), *value ) else: setAttr( str(self), value ) def _get( self ): """#WOW! the api is SUPER dumb if you want to figure out how to get the value of an attribute... mobject = self.attribute() apiType = mobject.apiType() if mobject.hasFn( MFn.kNumericData ): dFn = MFnNumericData( mobject ) dFnType = dFn.type() if dFnType == MFnNumericData.kBoolean: return self.asBool() elif dFnType in ( MFnNumericData.kInt, MFnNumericData.kShort, MFnNumericData.kLong ): return self.asInt() elif dFnType in ( MFnNumericData.kFloat, MFnNumericData.kDouble ): return self.asFloat() elif mobject.hasFn( MFn.kStringData ): if dFnType == MFnStringData.kString: return self.asString() """ val = getAttr( str(self) ) #use mel instead! if isinstance( val, list ): return val[ 0 ] return val MPlug.GetValue = _get MPlug.SetValue = _set def _hash( self ): ''' get the node hash, and add the hash of the attribute name ie: the name of the attribute, not the path to the attribute ''' return hash( self.node() ) + hash( '.'.join( self.name().split( '.' )[ 1: ] ) ) MPlug.__hash__ = _hash def _longName( self ): return self.partialName( False, False, False, False, False, True ) MPlug.longName = _longName MPlug.shortName = MPlug.partialName def _aliasName( self ): #definedAliass = cmd.aliasAttr( self.node(), q=True ) #longName = self.longName() #shortName = self.shortName() #if longName in definedAliass or shortName in definedAliass: #return self.partialName( False, False, False, True ) #return longName return '.'.join( self.name().split( '.' )[ 1: ] ) MPlug.alias = _aliasName def _isHidden( self ): if self.isElement(): return bool( cmd.attributeQuery( self.array().longName(), n=self.node(), hidden=True ) ) return bool( cmd.attributeQuery( self.longName(), n=self.node(), hidden=True ) ) MPlug.isHidden = _isHidden ### MVECTOR, MMATRIX CUSTOMIZATIONS ### def __asNice( self ): return Vector( [self.x, self.y, self.z] ) MVector.asNice = __asNice MPoint.asNice = __asNice def __asNice( self ): values = [] for i in range( 4 ): for j in range( 4 ): values.append( self(i, j) ) return Matrix( values ) MMatrix.asNice = __asNice def __str( self ): return str( self.asNice() ) MVector.__str__ = __str MVector.__repr__ = __str MVector.__unicode__ = __str MPoint.__str__ = __str MPoint.__repr__ = __str MPoint.__unicode__ = __str def _asPy( self ): return Vector( (self.x, self.y, self.z) ) MVector.asPy = _asPy def __str( self ): return str( self.asNice() ) MMatrix.__str__ = __str MMatrix.__repr__ = __str MMatrix.__unicode__ = __str def _asPy( self, size=4 ): values = [] for i in range( size ): for j in range( size ): values.append( self( i, j ) ) return Matrix( values, size ) MMatrix.asPy = _asPy def __asMaya( self ): return MVector( *self ) Vector.asMaya = __asMaya ### UTILITIES ### def castToMObjects( items ): ''' is a reasonably efficient way to map a list of nodes to mobjects NOTE: this returns a generator - use list( castToMObjects( nodes ) ) to collapse the generator ''' sel = MSelectionList() newItems = [] for n, item in enumerate( items ): sel.add( item ) mobject = MObject() sel.getDependNode( n, mobject ) newItems.append( mobject ) return newItems def getSelected(): items = [] sel = MSelectionList() MGlobal.getActiveSelectionList( sel ) for n in range( sel.length() ): mobject = MObject() sel.getDependNode( n, mobject ) items.append( mobject ) return items def iterAll(): ''' returns a fast generator that visits all nodes of this class's type in the scene ''' iterNodes = MItDependencyNodes() getItem = iterNodes.thisNode next = iterNodes.next #cache next method for faster access inside the generator while not iterNodes.isDone(): yield getItem() next() def lsAll(): return list( iterAll() ) def ls_( *a, **kw ): ''' wraps the ls mel command so that it returns mobject instances instead of strings ''' return castToMObjects( cmd.ls( *a, **kw ) or [] ) def filterByType( items, apiTypes ): ''' returns a generator that will yield all items in the given list that match the given apiType enums ''' if not isinstance( apiTypes, (list, tuple) ): apiTypes = [ apiTypes ] for item in items: if item.apiType() in apiTypes: yield item def getNodesCreatedBy( function, *args, **kwargs ): ''' returns a 2-tuple containing all the nodes created by the passed function, and the return value of said function ''' #construct the node created callback newNodeHandles = [] def newNodeCB( newNode, data ): newNodeHandles.append( MObjectHandle( newNode ) ) def remNodeCB( remNode, data ): remNodeHandle = MObjectHandle( remNode ) if remNodeHandle in newNodeHandles: newNodeHandles.remove( remNodeHandle ) newNodeCBMsgId = MDGMessage.addNodeAddedCallback( newNodeCB ) remNodeCBMsgId = MDGMessage.addNodeRemovedCallback( remNodeCB ) ret = function( *args, **kwargs ) MMessage.removeCallback( newNodeCBMsgId ) MMessage.removeCallback( remNodeCBMsgId ) newNodes = [ h.object() for h in newNodeHandles ] return newNodes, ret def iterTopNodes( nodes ): kDagNode = MFn.kDagNode for node in castToMObjects( nodes ): if node.hasFn( kDagNode ): if node.getParent() is None: yield node def iterParents( obj ): parent = cmd.listRelatives( obj, p=True, pa=True ) while parent is not None: yield parent[ 0 ] parent = cmd.listRelatives( parent[ 0 ], p=True, pa=True ) def sortByHierarchy( objs ): sortedObjs = [] for o in objs: pCount = len( list( iterParents( o ) ) ) sortedObjs.append( (pCount, o) ) sortedObjs.sort() return [ o[ 1 ] for o in sortedObjs ] def stripTrailingDigits( name ): trailingDigits = [] if name[ -1 ].isdigit(): for idx, char in enumerate( reversed( name ) ): if not char.isdigit(): return name[ :-idx ] return name def iterNonUniqueNames(): iterNodes = MItDag() #type=MFn.kTransform ) #NOTE: only dag objects can have non-unique names... despite the fact that the hasUniqueName method lives on MFnDependencyNode (wtf?!) while not iterNodes.isDone(): mobject = iterNodes.currentItem() if not MFnDependencyNode( mobject ).hasUniqueName(): #thankfully instantiating MFn objects isn't slow - just MObject and MDagPath yield mobject iterNodes.next() def fixNonUniqueNames(): rename = cmd.rename for dagPath in iterNonUniqueNames(): name = dagPath.partialPathName() newName = rename( name, stripTrailingDigits( name.split( '|' )[ -1 ] ) +'#' ) print 'RENAMED:', name, newName def selectNonUniqueNames(): cmd.select( cl=True ) theNodes = map( str, iterNonUniqueNames() ) if theNodes: cmd.select( theNodes ) #end
Python
from baseSkeletonBuilder import * class Arm(SkeletonPart): HAS_PARITY = True @classmethod def _build( cls, parent=None, buildClavicle=True, **kw ): idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] parent = getParent( parent ) allJoints = [] dirMult = idx.asMultiplier() parityName = idx.asName() if buildClavicle: clavicle = createJoint( 'clavicle%s' % parityName ) cmd.parent( clavicle, parent, relative=True ) move( dirMult * partScale / 50.0, partScale / 10.0, partScale / 25.0, clavicle, r=True, ws=True ) allJoints.append( clavicle ) parent = clavicle bicep = createJoint( 'bicep%s' % parityName ) cmd.parent( bicep, parent, relative=True ) move( dirMult * partScale / 10.0, 0, 0, bicep, r=True, ws=True ) elbow = createJoint( 'elbow%s' % parityName ) cmd.parent( elbow, bicep, relative=True ) move( dirMult * partScale / 5.0, 0, -partScale / 20.0, elbow, r=True, ws=True ) wrist = createJoint( 'wrist%s' % parityName ) cmd.parent( wrist, elbow, relative=True ) move( dirMult * partScale / 5.0, 0, partScale / 20.0, wrist, r=True, ws=True ) setAttr( '%s.rz' % bicep, dirMult * 45 ) jointSize( bicep, 2 ) jointSize( wrist, 2 ) return allJoints + [ bicep, elbow, wrist ] def _buildPlacers( self ): return [] def visualize( self ): scale = self.getBuildScale() / 10.0 plane = polyCreateFacet( ch=False, tx=True, s=1, p=((0, 0, -scale), (0, 0, scale), (self.getParityMultiplier() * 2 * scale, 0, 0)) ) cmd.parent( plane, self.wrist, relative=True ) cmd.parent( listRelatives( plane, shapes=True, pa=True ), self.wrist, add=True, shape=True ) delete( plane ) @property def clavicle( self ): return self[ 0 ] if len( self ) > 3 else None @property def bicep( self ): return self[ -3 ] @property def elbow( self ): return self[ -2 ] @property def wrist( self ): return self[ -1 ] def _align( self, _initialAlign=False ): parity = self.getParity() normal = getPlaneNormalForObjects( self.bicep, self.elbow, self.wrist ) normal *= parity.asMultiplier() if self.clavicle: parent = getNodeParent( self.clavicle ) if parent: alignAimAtItem( self.clavicle, self.bicep, parity, upType='objectrotation', worldUpObject=parent, worldUpVector=MAYA_FWD ) alignAimAtItem( self.bicep, self.elbow, parity, worldUpVector=normal ) alignAimAtItem( self.elbow, self.wrist, parity, worldUpVector=normal ) if _initialAlign: autoAlignItem( self.wrist, parity, worldUpVector=normal ) else: alignPreserve( self.wrist ) for i in self.getOrphanJoints(): alignItemToLocal( i ) def getIkFkItems( self ): return self.bicep, self.elbow, self.wrist #end
Python
def trackableTypeFactory( metaclassSuper=type ): ''' returns a metaclass that will track subclasses. All classes of the type returned by this factory will have the following class methods implemented: IterSubclasses() GetSubclasses() GetNamedSubclass( name ) usage: class SomeClass( metaclass=trackableTypeFactory() ): pass class SomSubclass( SomeClass ): pass print SomeClass.GetSubclasses() NOTE: the metaclass that is returned inherits from the metaclassSuper arg, which defaults to type. So if you want to mix together metaclasses, you can inherit from a subclass of type ''' _SUB_CLASS_LIST = [] #stores the list of all subclasses in the order they're created _SUB_CLASS_DICT = {} #makes for fast lookups of named subclasses def IterSubclasses( cls ): ''' iterates over all subclasses ''' for c in _SUB_CLASS_LIST: if c is cls: #skip the class we're calling this on continue if issubclass( c, cls ): yield c def GetSubclasses( cls ): ''' returns a list of subclasses ''' return list( cls.IterSubclasses() ) def GetNamedSubclass( cls, name ): ''' returns the first subclass found with the given name ''' return _SUB_CLASS_DICT.get( name, None ) class _TrackableType(metaclassSuper): def __new__( cls, name, bases, attrs ): newCls = metaclassSuper.__new__( cls, name, bases, attrs ) _SUB_CLASS_LIST.append( newCls ) _SUB_CLASS_DICT.setdefault( name, newCls ) #set default so subclass name clashes are resolved using the first definition parsed #insert the methods above into the newCls unless the names are already taken on the newCls if not hasattr( newCls, 'IterSubclasses' ): newCls.IterSubclasses = classmethod( IterSubclasses ) if not hasattr( newCls, 'GetSubclasses' ): newCls.GetSubclasses = classmethod( GetSubclasses ) if not hasattr( newCls, 'GetNamedSubclass' ): newCls.GetNamedSubclass = classmethod( GetNamedSubclass ) return newCls return _TrackableType def interfaceTypeFactory( metaclassSuper=type ): ''' returns an "Interface" metaclass. Interface classes work as you'd expect. Every method implemented on the interface class must be implemented on subclasses otherwise a TypeError will be raised at class creation time. usage: class IFoo( metaclass=interfaceTypeFactory() ): def bar( self ): pass subclasses must implement the bar method NOTE: the metaclass that is returned inherits from the metaclassSuper arg, which defaults to type. So if you want to mix together metaclasses, you can inherit from a subclass of type. For example: class IFoo( metaclass=interfaceTypeFactory( trackableTypeFactory() ) ): def bar( self ): pass class Foo(IFoo): def bar( self ): return None print( IFoo.GetSubclasses() ) ''' class _AbstractType(metaclassSuper): _METHODS_TO_IMPLEMENT = None _INTERFACE_CLASS = None def _(): pass _FUNC_TYPE = type( _ ) def __new__( cls, name, bases, attrs ): newCls = metaclassSuper.__new__( cls, name, bases, attrs ) #if this hasn't been defined, then cls must be the interface class if cls._METHODS_TO_IMPLEMENT is None: cls._METHODS_TO_IMPLEMENT = methodsToImplement = [] cls._INTERFACE_CLASS = newCls for name, obj in attrs.items(): if type( obj ) is cls._FUNC_TYPE: methodsToImplement.append( name ) #otherwise it is a subclass that should be implementing the interface else: if cls._INTERFACE_CLASS in bases: for methodName in cls._METHODS_TO_IMPLEMENT: #if the newCls' methodName attribute is the same method as the interface #method, then the method hasn't been implemented. Its done this way because #the newCls may be inheriting from multiple classes, one of which satisfies #the interface - so we can't just look up the methodName in the attrs dict if getattr( newCls, methodName, None ).im_func is getattr( cls._INTERFACE_CLASS, methodName ).im_func: raise TypeError( "The class %s doesn't implement the required method %s!" % (name, methodName) ) return newCls return _AbstractType def trackableClassFactory( superClass=object ): ''' returns a class that tracks subclasses. for example, if you had classB(classA) ad you wanted to track subclasses, you could do this: class classB(trackableClassFactory( classA )): ... a classmethod called GetSubclasses is created in the returned class for querying the list of subclasses NOTE: this is a convenience function for versions of python that don't support the metaclass class constructor keyword. Python 2.6 and before need you to use the __metaclass__ magic class attribute to define a metaclass ''' class TrackableClass(superClass): __metaclass__ = trackableTypeFactory() return TrackableClass #end
Python
import cProfile as prof import pstats import os import time def d_profile(f): ''' writes out profiling info on the decorated function. the profile results are dumped in a file called something like "_profile__<moduleName>.<functionName>.txt" ''' def newFunc( *a, **kw ): def run(): f( *a, **kw ) baseDir = os.path.split( __file__ )[0] tmpFile = os.path.join( baseDir, 'profileResults.tmp' ) prof.runctx( 'run()', globals(), locals(), tmpFile ) try: module = f.__module__ except AttributeError: module = 'NOMODULE' dumpFile = os.path.join( baseDir, '_profile__%s.%s.txt' % (module, f.__name__) ) dumpF = file( dumpFile, 'w' ) stats = pstats.Stats( tmpFile ) stats.sort_stats( 'time', 'calls', 'name' ) stats.stream = dumpF stats.print_stats() stats.sort_stats( 'cumulative', 'time' ) stats.print_stats() dumpF.close() #remove the tmpFile os.remove( tmpFile ) print 'LOGGED PROFILING STATS TO', dumpFile newFunc.__name__ = f.__name__ newFunc.__doc__ = f.__doc__ return newFunc def d_timer(f): ''' simply reports the time taken by the decorated function ''' def newFunc( *a, **kw ): s = time.clock() ret = f( *a, **kw ) print 'Time Taken by %s: %0.3g' % (f.__name__, time.clock()-s) return ret newFunc.__name__ = f.__name__ newFunc.__doc__ = f.__doc__ return newFunc #end
Python
import sys import skeletonBuilder import baseRigPrimitive from filesystem import Path from skeletonBuilder import * from baseRigPrimitive import * __author__ = 'hamish@macaronikazoo.com' RIG_PART_SCRIPT_PREFIX = 'rigPrim_' ### !!! DO NOT IMPORT RIG SCRIPTS BELOW THIS LINE !!! ### def _iterRigPartScripts(): for p in sys.path: p = Path( p ) if 'maya' in p: # for f in p.files(): if f.hasExtension( 'py' ): if f.name().startswith( RIG_PART_SCRIPT_PREFIX ): yield f for f in _iterRigPartScripts(): __import__( f.name() ) def _setupSkeletonPartRigMethods(): ''' sets up the rig method associations on the skeleton parts. This is a list on each skeleton part containing the rigging methods that are compatible with that skeleton part ''' _rigMethodDict = {} for cls in RigPart.GetSubclasses(): try: assoc = cls.SKELETON_PRIM_ASSOC except AttributeError: continue if assoc is None: continue for partCls in assoc: if partCls is None: continue try: _rigMethodDict[ partCls ].append( (cls.PRIORITY, cls) ) except KeyError: _rigMethodDict[ partCls ] = [ (cls.PRIORITY, cls) ] for partCls, rigTypes in _rigMethodDict.iteritems(): rigTypes.sort() rigTypes = [ rigType for priority, rigType in rigTypes ] partCls.RigTypes = rigTypes _setupSkeletonPartRigMethods() #end
Python
from baseSkeletonBuilder import * class Spine(SkeletonPart): HAS_PARITY = False @classmethod def _build( cls, parent=None, count=3, direction='y', **kw ): idx = kw[ 'idx' ] partScale = kw[ 'partScale' ] parent = getParent( parent ) directionAxis = Axis.FromName( direction ) allJoints = [] prevJoint = str( parent ) posInc = float( partScale ) / 2 / (count + 2) moveList = list( directionAxis.asVector() * posInc ) for n in range( count ): j = createJoint( 'spine%s%d' % ('' if idx == 0 else '%d_' % idx, n+1) ) cmd.parent( j, prevJoint, relative=True ) move( moveList[0], moveList[1], moveList[2], j, r=True, ws=True ) allJoints.append( j ) prevJoint = j jointSize( j, 2 ) return allJoints def _align( self, _initialAlign=False ): for n, item in enumerate( self[ :-1 ] ): alignAimAtItem( item, self[ n+1 ] ) #if there is a head part parented to this part, then use it as a look at for the end joint childParts = self.getChildParts() hasHeadPartAsChild = False headPart = None HeadCls = SkeletonPart.GetNamedSubclass( 'Head' ) or type( None ) for p in childParts: if isinstance( p, HeadCls ): headPart = p break if headPart is None: autoAlignItem( self.end ) else: alignAimAtItem( self.end, headPart.base ) #end
Python
from typeFactories import interfaceTypeFactory from baseRigPrimitive import * from apiExtensions import cmpNodes ARM_NAMING_SCHEME = 'arm', 'bicep', 'elbow', 'wrist' LEG_NAMING_SCHEME = 'leg', 'thigh', 'knee', 'ankle' class SwitchableMixin(object): ''' NOTE: we can't make this an interface class because rig part classes already have a pre-defined metaclass... :( ''' def __notimplemented( self ): raise NotImplemented( "This baseclass method hasn't been implemented on the %s class" % type( self ).__name__ ) def switchToFk( self, key=False ): ''' should implement the logic to switch this chain from IK to FK ''' self.__notimplemented() def switchToIk( self, key=False, _isBatchMode=False ): ''' should implement the logic to switch this chain from FK to IK ''' self.__notimplemented() def setupIkFkVisibilityConditions( ikBlendAttrpath, ikControls, fkControls ): ikControl = ikBlendAttrpath.split( '.' )[0] visCondFk = createNode( 'condition' ) visCondFk = rename( visCondFk, '%s_fkVis#' % ikControl ) visCondIk = createNode( 'condition' ) visCondIk = rename( visCondIk, '%s_ikVis#' % ikControl ) connectAttr( ikBlendAttrpath, '%s.firstTerm' % visCondFk ) connectAttr( ikBlendAttrpath, '%s.firstTerm' % visCondIk ) setAttr( '%s.secondTerm' % visCondFk, 1 ) setAttr( '%s.secondTerm' % visCondIk, 0 ) setAttr( '%s.operation' % visCondFk, 3 ) #this is the >= operator setAttr( '%s.operation' % visCondIk, 5 ) #this is the <= operator for c in fkControls: connectAttr( '%s.outColorR' % visCondFk, '%s.v' % c ) for c in ikControls: connectAttr( '%s.outColorR' % visCondIk, '%s.v' % c ) class IkFkBase(PrimaryRigPart, SwitchableMixin): ''' super class functionality for biped limb rigs - legs, arms and even some quadruped rigs inherit from this class ''' NAMED_NODE_NAMES = 'ikSpace', 'fkSpace', 'ikHandle', 'endOrient', 'poleTrigger' def buildBase( self, nameScheme=ARM_NAMING_SCHEME, alignEnd=False ): self.nameScheme = nameScheme self.alignEnd = alignEnd self.bicep, self.elbow, self.wrist = bicep, elbow, wrist = self.getSkeletonPart().getIkFkItems() colour = self.getParityColour() suffix = self.getSuffix() #build the fk controls self.fkSpace = buildAlignedNull( bicep, "fk_%sSpace%s" % (nameScheme[ 0 ], suffix) ) self.driverUpper = buildControl( "fk_%sControl%s" % (nameScheme[ 1 ], suffix), bicep, PivotModeDesc.MID, shapeDesc=ShapeDesc( 'sphere' ), colour=colour, asJoint=True, oriented=False, scale=self.scale, parent=self.fkSpace ) self.driverMid = buildControl( "fk_%sControl%s" % (nameScheme[ 2 ], suffix), elbow, PivotModeDesc.MID, shapeDesc=ShapeDesc( 'sphere' ), colour=colour, asJoint=True, oriented=False, scale=self.scale, parent=self.driverUpper ) self.driverLower = buildControl( "fk_%sControl%s" % (nameScheme[ 3 ], suffix), PlaceDesc( wrist, wrist if alignEnd else None ), shapeDesc=ShapeDesc( 'sphere' ), colour=colour, asJoint=True, oriented=False, constrain=False, scale=self.scale, parent=self.driverMid ) self.fkControls = self.driverUpper, self.driverMid, self.driverLower attrState( self.fkControls, ('t', 'radi'), *LOCK_HIDE ) #build the ik controls self.ikSpace = buildAlignedNull( self.wrist, "ik_%sSpace%s" % (self.nameScheme[ 0 ], suffix), parent=self.getWorldControl() ) self.ikHandle = asMObject( cmd.ikHandle( fs=1, sj=self.driverUpper, ee=self.driverLower, solver='ikRPsolver' )[0] ) self.control = limbControl = buildControl( '%sControl%s' % (self.nameScheme[ 0 ], suffix), PlaceDesc( self.wrist, self.wrist if self.alignEnd else None ), shapeDesc=ShapeDesc( 'cube' ), colour=colour, scale=self.scale, constrain=False, parent=self.ikSpace ) rename( self.ikHandle, '%sIkHandle%s' % (self.nameScheme[0], suffix) ) xform( self.control, p=True, rotateOrder='yzx' ) setAttr( '%s.snapEnable' % self.ikHandle, False ) setAttr( '%s.v' % self.ikHandle, False ) addAttr( self.control, ln='ikBlend', shortName='ikb', dv=1, min=0, max=1, at='double' ) setAttr( '%s.ikBlend' % self.control, keyable=True ) connectAttr( '%s.ikBlend' % self.control, '%s.ikBlend' % self.ikHandle ) attrState( self.ikHandle, 'v', *LOCK_HIDE ) parent( self.ikHandle, self.getPartsNode() ) parentConstraint( self.control, self.ikHandle ) #build the pole control polePos = rigUtils.findPolePosition( self.driverLower, self.driverMid, self.driverUpper, 5 ) self.poleControl = buildControl( "%s_poleControl%s" % (self.nameScheme[ 0 ], suffix), PlaceDesc( self.elbow, PlaceDesc.WORLD ), shapeDesc=ShapeDesc( 'sphere', None ), colour=colour, constrain=False, parent=self.getWorldControl(), scale=self.scale*0.5 ) self.poleControlSpace = getNodeParent( self.poleControl ) attrState( self.poleControlSpace, 'v', lock=False, show=True ) move( polePos[0], polePos[1], polePos[2], self.poleControlSpace, a=True, ws=True, rpr=True ) move( polePos[0], polePos[1], polePos[2], self.poleControl, a=True, ws=True, rpr=True ) makeIdentity( self.poleControlSpace, a=True, t=True ) setAttr( '%s.v' % self.poleControl, True ) poleVectorConstraint( self.poleControl, self.ikHandle ) #build the pole selection trigger self.lineNode = buildControl( "%s_poleSelectionTrigger%s" % (self.nameScheme[ 0 ], suffix), shapeDesc=ShapeDesc( 'sphere', None ), colour=ColourDesc( 'darkblue' ), scale=self.scale, constrain=False, oriented=False, parent=self.ikSpace ) self.lineStart, self.lineEnd, self.lineShape = buildAnnotation( self.lineNode ) parent( self.lineStart, self.poleControl ) delete( pointConstraint( self.poleControl, self.lineStart ) ) pointConstraint( self.elbow, self.lineNode ) attrState( self.lineNode, ('t', 'r'), *LOCK_HIDE ) setAttr( '%s.template' % self.lineStart, 1 ) #make the actual line unselectable #setup constraints to the wrist - it is handled differently because it needs to blend between the ik and fk chains (the other controls are handled by maya) self.endOrientParent = buildAlignedNull( self.wrist, "%s_follow%s_space" % (self.nameScheme[ 3 ], suffix), parent=self.getPartsNode() ) self.endOrient = buildAlignedNull( self.wrist, "%s_follow%s" % (self.nameScheme[ 3 ], suffix), parent=self.endOrientParent ) pointConstraint( self.driverLower, self.wrist ) orientConstraint( self.endOrient, self.wrist, mo=True ) setItemRigControl( self.wrist, self.endOrient ) setNiceName( self.endOrient, 'Fk %s' % self.nameScheme[3] ) self.endOrientSpaceConstraint = parentConstraint( self.control, self.endOrientParent, weight=0, mo=True )[ 0 ] self.endOrientSpaceConstraint = parentConstraint( self.driverLower, self.endOrientParent, weight=0, mo=True )[ 0 ] #constraints to drive the "wrist follow" mode self.endOrientConstraint = parentConstraint( self.endOrientParent, self.endOrient )[0] self.endOrientConstraint = parentConstraint( self.driverLower, self.endOrient, mo=True )[0] addAttr( self.control, ln='orientToIk', at='double', min=0, max=1, dv=1 ) attrState( self.control, 'orientToIk', keyable=True, show=True ) endOrientAttrs = listAttr( self.endOrientConstraint, ud=True ) expression( s='%s.%s = %s.orientToIk;\n%s.%s = 1 - %s.orientToIk;' % (self.endOrientConstraint, endOrientAttrs[0], self.control, self.endOrientConstraint, endOrientAttrs[1], self.control), n='endOrientConstraint_on_off' ) endOrientSpaceAttrs = listAttr( self.endOrientSpaceConstraint, ud=True ) expression( s='%s.%s = %s.ikBlend;\n%s.%s = 1 - %s.ikBlend;' % (self.endOrientSpaceConstraint, endOrientSpaceAttrs[0], self.control, self.endOrientSpaceConstraint, endOrientSpaceAttrs[1], self.control), n='endOrientSpaceConstraint_on_off' ) #build expressions for fk blending and control visibility self.fkVisCond = fkVisCond = shadingNode( 'condition', asUtility=True ) self.poleVisCond = poleVisCond = shadingNode( 'condition', asUtility=True ) connectAttr( '%s.ikBlend' % self.control, '%s.firstTerm' % self.fkVisCond, f=True ) connectAttr( '%s.ikBlend' % self.control, '%s.firstTerm' % self.poleVisCond, f=True ) connectAttr( '%s.outColorG' % self.poleVisCond, '%s.v' % self.lineNode, f=True ) connectAttr( '%s.outColorG' % self.poleVisCond, '%s.v' % self.poleControlSpace, f=True ) connectAttr( '%s.outColorG' % self.poleVisCond, '%s.v' % self.control, f=True ) setAttr( '%s.secondTerm' % self.fkVisCond, 1 ) driverUpper, driverMid, driverLower = self.driverUpper, self.driverMid, self.driverLower expression( s='if ( %(limbControl)s.ikBlend > 0 && %(limbControl)s.orientToIk < 1 ) %(driverLower)s.visibility = 1;\nelse %(driverLower)s.visibility = %(fkVisCond)s.outColorG;' % locals(), n='wrist_visSwitch' ) for driver in (self.driverUpper, self.driverMid): for shape in listRelatives( driver, s=True, pa=True ): connectAttr( '%s.outColorR' % self.fkVisCond, '%s.v' % shape, f=True ) #add set pole to fk pos command to pole control poleTrigger = Trigger( self.poleControl ) poleConnectNums = [ poleTrigger.connect( c ) for c in self.fkControls ] idx_toFK = poleTrigger.setMenuInfo( None, "move to FK position", 'zooVectors;\nfloat $pos[] = `zooFindPolePosition "-start %%%s -mid %%%s -end %%%s"`;\nmove -rpr $pos[0] $pos[1] $pos[2] #;' % tuple( poleConnectNums ) ) poleTrigger.setMenuInfo( None, "move to FK pos for all keys", 'source zooKeyCommandsWin;\nzooSetKeyCommandsWindowCmd "eval(zooPopulateCmdStr(\\\"#\\\",(zooGetObjMenuCmdStr(\\\"#\\\",%%%d)),{}))";' % idx_toFK ) limbTrigger = Trigger( self.control ) handleNum = limbTrigger.connect( self.ikHandle ) poleNum = limbTrigger.connect( self.poleControl ) lowerNum = limbTrigger.connect( self.driverLower ) fkIdx = limbTrigger.createMenu( "switch to FK", "zooAlign \"\";\nzooAlignFK \"-ikHandle %%%d -offCmd setAttr #.ikBlend 0\";\nselect %%%d;" % (handleNum, lowerNum) ) limbTrigger.createMenu( "switch to FK for all keys", 'source zooKeyCommandsWin;\nzooSetKeyCommandsWindowCmd "eval(zooPopulateCmdStr(\\\"#\\\",(zooGetObjMenuCmdStr(\\\"#\\\",%%%d)),{}))";' % fkIdx ) ikIdx = limbTrigger.createMenu( "switch to IK", 'zooAlign "";\nzooAlignIK "-ikHandle %%%d -pole %%%d -offCmd setAttr #.ikBlend 1;";' % (handleNum, poleNum) ) limbTrigger.createMenu( "switch to IK for all keys", 'source zooKeyCommandsWin;\nzooSetKeyCommandsWindowCmd "eval(zooPopulateCmdStr(\\\"#\\\",(zooGetObjMenuCmdStr(\\\"#\\\",%%%d)),{}))";' % ikIdx ) #add all zooObjMenu commands to the fk controls for fk in self.fkControls: fkTrigger = Trigger( fk ) c1 = fkTrigger.connect( self.ikHandle ) c2 = fkTrigger.connect( self.poleControl ) fkTrigger.createMenu( 'switch to IK', 'zooAlign "";\nstring $cs[] = `listConnections %%%d.ikBlend`;\nzooAlignIK ("-ikHandle %%%d -pole %%%d -control "+ $cs[0] +" -offCmd setAttr "+ $cs[0] +".ikBlend 1;" );' % (c1, c1, c2) ) createLineOfActionMenu( [self.control] + list( self.fkControls ), (self.elbow, self.wrist) ) #add trigger commands Trigger.CreateTrigger( self.lineNode, Trigger.PRESET_SELECT_CONNECTED, [ self.poleControl ] ) setAttr( '%s.displayHandle' % self.lineNode, True ) #turn unwanted transforms off, so that they are locked, and no longer keyable attrState( self.poleControl, 'r', *LOCK_HIDE ) def buildAllPurposeLocator( self, nodePrefix ): allPurposeObj = spaceLocator( name="%s_all_purpose_loc%s" % (nodePrefix, self.getSuffix()) )[ 0 ] attrState( allPurposeObj, 's', *LOCK_HIDE ) attrState( allPurposeObj, 'v', *HIDE ) parent( allPurposeObj, self.getWorldControl() ) return allPurposeObj def getFkControls( self ): return self.getControl( 'fkUpper' ), self.getControl( 'fkMid' ), self.getControl( 'fkLower' ) def getIkControls( self ): return self.getControl( 'control' ), self.getControl( 'poleControl' ), self.getControl( 'ikHandle' ) @d_unifyUndo def switchToFk( self, key=False ): control, poleControl, handle = self.getIkControls() attrName = 'ikBlend' onValue = 1 offValue = 0 joints = self.getFkControls() if handle is None or not objExists( handle ): printWarningStr( "no ikHandle specified" ) return #make sure ik is on before querying rotations setAttr( '%s.%s' % (control, attrName), onValue ) rots = [] for j in joints: rot = getAttr( "%s.r" % j )[0] rots.append( rot ) #now turn ik off and set rotations for the joints setAttr( '%s.%s' % (control, attrName), offValue ) for j, rot in zip( joints, rots ): for ax, r in zip( ('x', 'y', 'z'), rot ): if getAttr( '%s.r%s' % (j, ax), se=True ): setAttr( '%s.r%s' % (j, ax), r ) alignFast( joints[2], handle ) if key: setKeyframe( joints ) setKeyframe( '%s.%s' % (control, attrName) ) @d_unifyUndo def switchToIk( self, key=False, _isBatchMode=False ): control, poleControl, handle = self.getIkControls() attrName = 'ikBlend' onValue = 1 joints = self.getFkControls() if handle is None or not objExists( handle ): printWarningStr( "no ikHandle specified" ) return alignFast( control, joints[2] ) if poleControl: if objExists( poleControl ): pos = findPolePosition( joints[2], joints[1], joints[0] ) move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True ) setKeyframe( poleControl ) setAttr( '%s.%s' % (control, attrName), onValue ) if key: setKeyframe( control, at=('t', 'r') ) if not _isBatchMode: setKeyframe( control, at=attrName ) #end
Python
from filesystem import Path import os import sys import dependencies import api import maya import baseMelUI import maya.cmds as cmd def flush(): pluginPaths = map( Path, api.mel.eval( 'getenv MAYA_PLUG_IN_PATH' ).split( ';' ) ) #NOTE: os.environ is different from the getenv call, and getenv isn't available via python... yay! #before we do anything we need to see if there are any plugins in use that are python scripts - if there are, we need to ask the user to close the scene #now as you might expect maya is a bit broken here - querying the plugins in use doesn't return reliable information - instead we ask for all loaded #plugins, to which maya returns a list of extension-less plugin names. We then have to map those names back to disk by searching the plugin path and #determining whether the plugins are binary or scripted plugins, THEN we need to see which the scripted ones are unloadable. loadedPluginNames = cmd.pluginInfo( q=True, ls=True ) or [] loadedScriptedPlugins = [] for pluginName in loadedPluginNames: for p in pluginPaths: possiblePluginPath = (p / pluginName).setExtension( 'py' ) if possiblePluginPath.exists(): loadedScriptedPlugins.append( possiblePluginPath[-1] ) initialScene = None for plugin in loadedScriptedPlugins: if not cmd.pluginInfo( plugin, q=True, uo=True ): BUTTONS = YES, NO = 'Yes', 'NO' ret = cmd.confirmDialog( t='Plugins in Use!', m="Your scene has python plugins in use - these need to be unloaded to properly flush.\n\nIs it cool if I close the current scene? I'll prompt to save your scene...\n\nNOTE: No flushing has happened yet!", b=BUTTONS, db=NO ) if ret == NO: print "!! FLUSH ABORTED !!" return initialScene = cmd.file( q=True, sn=True ) #prompt to make new scene if there are unsaved changes... api.mel.saveChanges( 'file -f -new' ) break #now unload all scripted plugins for plugin in loadedScriptedPlugins: cmd.unloadPlugin( plugin ) #we need to unload the plugin so that it gets reloaded (it was flushed) - it *may* be nessecary to handle the plugin reload here, but we'll see how things go for now #lastly, close all windows managed by baseMelUI - otherwise callbacks may fail... for melUI in baseMelUI.BaseMelWindow.IterInstances(): melUI.delete() #determine the location of maya lib files - we don't want to flush them either mayaLibPath = Path( maya.__file__ ).up( 2 ) #flush all modules dependencies.flush( [ mayaLibPath ] ) if initialScene and not cmd.file( q=True, sn=True ): if Path( initialScene ).exists(): cmd.file( initialScene, o=True ) print "WARNING: You'll need to close and re-open any python based tools that are currently open..." def reconnect(): #try to import wing import wingdbstub wingdbstub.Ensure() import time try: debugger = wingdbstub.debugger except AttributeError: print "No debugger found!" else: if debugger is not None: debugger.StopDebug() time.sleep( 1 ) debugger.StartDebug() #end
Python
from baseMelUI import * from filesystem import Path, Callback from common import printWarningStr import api, presetsUI PRESET_ID_STR = 'zoo' PRESET_EXTENSION = 'filter' class FileScrollList(MelObjectScrollList): def __init__( self, parent, *a, **kw ): self._rootDir = None self._displayRelativeToRoot = True MelObjectScrollList.__init__( self, parent, *a, **kw ) def itemAsStr( self, item ): if self._displayRelativeToRoot and self._rootDir: return str( Path( item ) - self._rootDir ) return str( item ) def getRootDir( self ): return self._rootDir def setRootDir( self, rootDir ): self._rootDir = Path( rootDir ) self.update() def getDisplayRelative( self ): return self._displayRelativeToRoot def setDisplayRelative( self, state=True ): self._displayRelativeToRoot = state self.update() class FileListLayout(MelVSingleStretchLayout): ENABLE_IMPORT = True ENABLE_REFERENCE = True def __new__( cls, parent, *a, **kw ): return BaseMelWidget.__new__( cls, parent ) def __init__( self, parent, directory=None, files=None, recursive=True ): self.expand = True self.padding = 2 self._files = [] self._recursive = recursive self._extensionSets = [] self._extensionsToDisplay = [] self._ignoreSubstrings = [ 'incrementalSave' ] self._enableOpen = True self._enableImport = True self._enableReference = True #this allows clients who subclass this class to set additional filter change callbacks - perhaps #for things like saving the filter string in user preferences, or doing additional work... self._filterChangeCB = None hLayout = MelHSingleStretchLayout( self ) MelLabel( hLayout, l='Directory' ) self.UI_dir = MelTextField( hLayout, tx=directory, cc=self.on_dirChange ) MelButton( hLayout, l='Browse', w=80, c=self.on_browse ) hLayout.setStretchWidget( self.UI_dir ) hLayout.layout() hLayout = MelHSingleStretchLayout( self ) MelLabel( hLayout, l='Filter' ) self.UI_filter = MelTextField( hLayout, cc=self.on_filterChanged ) if not self._extensionSets: for exts in self._extensionSets: self.UI_filter = MelOptionMenu( hLayout, l='', cc=self.on_changeExtensionSet ) self.UI_filter.append( ' '.join( exts ) ) hLayout.setStretchWidget( self.UI_filter ) hLayout.layout() self.UI_files = FileScrollList( self, ams=True, dcc=self.on_doubleClick, h=75 ) ### ADD POPUPS cmd.popupMenu( parent=self.UI_filter, b=3, pmc=self.popup_filterPresets ) cmd.popupMenu( parent=self.UI_files, b=3, pmc=self.popup_files ) if files is None: self.populateFiles() else: self.setFiles( files ) self.setStretchWidget( self.UI_files ) self.layout() def __contains__( self, item ): return item in self.UI_files def setDir( self, dir, update=True ): self.UI_dir.setValue( str( dir ), update ) def getDir( self ): return Path( self.UI_dir.getValue() ) def getRecursive( self ): return self._recursive def setRecursive( self, state=True, update=True ): self._recursive = state if update: self.populateFiles() def getExtensionsToDisplay( self ): return self._extensionsToDisplay[:] def setExtensionsToDisplay( self, extensionList, update=True ): self._extensionsToDisplay = extensionList[:] if update: self.populateFiles() def getIgnoreSubstrings( self ): return self._ignoreSubstrings[:] def setIgnoreSubstrings( self, substringList, update=True ): self._ignoreSubstrings = substringList[:] if update: self.populateFiles() def populateFiles( self ): self.setFiles( list( self.getDir().files( recursive=self.getRecursive() ) ) ) def getDisplayRelative( self ): return self.UI_files.getDisplayRelative() def setDisplayRelative( self, state=True ): self.UI_files.setDisplayRelative( state ) def getFilter( self ): return self.UI_filter.getValue() def setFilter( self, filterStr, update=True ): self.UI_filter.setValue( filterStr, update ) def setFilterChangeCB( self, cb ): self._filterChangeCB = cb def setSelectionChangeCB( self, cb ): self.UI_files.setChangeCB( cb ) def getSelectedFiles( self ): return self.UI_files.getSelectedItems() def setSelectedFiles( self, files, executeChangeCB=False ): #make sure all files are Path instances files = map( Path, files ) self.UI_files.selectItems( files, executeChangeCB ) def getFiles( self ): ''' returns the files being listed ''' return self.UI_files.getItems() def setFiles( self, files ): ''' sets the file list to the given iterable ''' self.UI_files.clear() self.addFiles( files ) def addFiles( self, files ): ''' adds files to the UI without clearing ''' self._files = [] for f in files: #if the file doesn't have the right extension - bail if self._extensionsToDisplay: if f.getExtension().lower() not in self._extensionsToDisplay: continue skip = False for invalid in self._ignoreSubstrings: if invalid.lower() in str( f ).lower(): skip = True break if skip: continue self._files.append( f ) self.UI_files.setItems( self._files ) ### MENU BUILDERS ### def popup_filterPresets( self, parent, *args ): cmd.setParent( parent, m=True ) cmd.menu( parent, e=True, dai=True ) hasItems = False allFilterPresets = presetsUI.listAllPresets( PRESET_ID_STR, PRESET_EXTENSION ) for locale, filterPresets in allFilterPresets.iteritems(): for item in filterPresets: itemName = item.name() cmd.menuItem( l=itemName, c=Callback( self.setFilter, itemName ) ) hasItems = True if hasItems: cmd.menuItem( d=True ) cmd.menuItem( l='clear', c=Callback( self.setFilter, '' ) ) if self.getFilter(): cmd.menuItem( d=True ) cmd.menuItem( l='save filter preset', c=self.on_filterSave ) cmd.menuItem( l='manager filter presets', c=self.on_filterManage ) def popup_files( self, parent, *args ): cmd.setParent( parent, m=True ) cmd.menu( parent, e=True, dai=True ) files = self.getSelectedFiles() if len( files ) == 1: if self._enableOpen: cmd.menuItem( l='open file', c=lambda *x: self.on_open( files[ 0 ] ) ) if self._enableImport: cmd.menuItem( l='import file', c=lambda *x: self.on_import( files[ 0 ] ) ) if self._enableReference: cmd.menuItem( l='reference file', c=lambda *x: self.on_reference( files[ 0 ] ) ) cmd.menuItem( d=True ) api.addExploreToMenuItems( files[ 0 ] ) else: cmd.menuItem( l="please select a single file" ) cmd.menuItem( d=True ) cmd.menuItem( cb=self.getDisplayRelative(), l="Display Relative Paths", c=lambda *x: self.setDisplayRelative( not self.getDisplayRelative() ) ) cmd.menuItem( cb=self.getRecursive(), l="Recursive Directory Listing", c=lambda *x: self.setRecursive( not self.getRecursive() ) ) ### EVENT CALLBACKS ### def on_open( self, theFile ): api.openFile( theFile ) def on_import( self, theFile ): api.importFile( theFile ) def on_reference( self, theFile ): api.referenceFile( theFile, 'ref' ) def on_dirChange( self, theDir=None ): if theDir is None: theDir = self.getDir() theDir = Path( theDir ) self.UI_files.setRootDir( theDir ) self.populateFiles() def on_browse( self, *args ): startDir = cmd.workspace( q=True, rootDirectory=True ) cmd.workspace( dir=startDir ) def tempCB( filename, filetype ): self.setDir( filename ) self.on_dirChange( filename ) cmd.fileBrowserDialog( mode=4, fileCommand=tempCB, an="Choose_Location" ) def on_filterChanged( self, *args ): self.UI_files.setFilter( self.UI_filter.getValue() ) if self._filterChangeCB: try: self._filterChangeCB() except: printWarningStr( "The filter change callback %s failed!" % self._filterChangeCB ) def on_changeExtensionSet( self, *args ): self._extensionsToDisplay = cmd.optionMenu( self.UI_filter, q=True, v=True ).split() self.populateFiles() def on_doubleClick( self, *args ): api.openFile( self.getSelectedFiles()[ 0 ] ) def on_filterSave( self, *args ): presetName = self.UI_filter.getValue() presetsUI.savePreset( presetsUI.LOCAL, PRESET_ID_STR, presetName, PRESET_EXTENSION ) def on_filterManage( self, *args ): presetsUI.load( PRESET_ID_STR, presetsUI.LOCAL, PRESET_EXTENSION ) class FileUIWindow(BaseMelWindow): WINDOW_NAME = 'fileUITestWindow' WINDOW_TITLE = 'File UI Test Window' DEFAULT_MENU = None DEFAULT_SIZE = 350, 400 def __init__( self ): editor = FileListLayout( self ) editor.setDir( cmd.workspace( q=True, rootDirectory=True ) ) self.show() #end
Python
from vectors import * from filesystem import Path, resolvePath, writeExportDict import time, datetime, names, filesystem TOOL_NAME = 'weightSaver' TOOL_VERSION = 2 DEFAULT_PATH = Path('%TEMP%/temp_skin.weights') TOL = 0.25 EXTENSION = 'weights' _MAX_RECURSE = 35 class SkinWeightException(Exception): pass class NoVertFound(Exception): pass class VertSkinWeight(Vector): ''' extends Vector to store a vert's joint list, weightlist and id ''' #can be used to store a dictionary so mesh names can be substituted at restore time when restoring by id MESH_NAME_REMAP_DICT = None #can be used to store a dictionary so joint names can be substituted at restore time JOINT_NAME_REMAP_DICT = None def __str__( self ): return '<%0.3f, %0.3f, %0.3f> %s' % (self[ 0 ], self[ 1 ], self[ 2 ], ', '.join( '%s: %0.2f' % d for d in zip( self.joints, self.weights ) )) __repr__ = __str__ def populate( self, meshName, vertIdx, jointList, weightList ): self.idx = vertIdx self.weights = tuple( weightList ) #convert to tuple to protect it from changing accidentally... self.__mesh = meshName self.__joints = tuple( jointList ) @property def mesh( self ): ''' If a MESH_NAME_REMAP Mapping object is present, the mesh name is re-mapped accordingly, otherwise the stored mesh name is returned. ''' if self.MESH_NAME_REMAP_DICT is None: return self.__mesh return self.MESH_NAME_REMAP_DICT.get( self.__mesh, self.__mesh ) @property def joints( self ): ''' Returns the list of joints the vert is skinned to. If a JOINT_NAME_REMAP Mapping object is present, names are re-mapped accordingly. ''' jointRemap = self.JOINT_NAME_REMAP_DICT if jointRemap is None: return self.__joints joints = [ jointRemap.get( j, j ) for j in self.__joints ] if len( joints ) != set( joints ): joints, self.weights = regatherWeights( joints, self.weights ) return joints def getVertName( self ): return '%s.%d' % (self.mesh, self.idx) class MayaVertSkinWeight(VertSkinWeight): ''' NOTE: this class needs to be defined in this file otherwise weight files saved from maya will be unavailable to external tools like modelpipeline because the maya scripts are invisible outside of maya. When unpickling objects - python needs to know what module to find the object's class in, so if that module is unavailable, a pickleException is raised when loading the file. ''' def getVertName( self ): return '%s.vtx[%d]' % (self.mesh, self.idx) class WeightSaveData(tuple): def __init__( self, data ): self.miscData, self.joints, self.jointHierarchies, self.weightData = data def getUsedJoints( self ): allJoints = set() for jData in self.weightData: allJoints |= set( jData.joints ) return allJoints def getUsedMeshes( self ): allMeshes = set() for d in self.weightData: allMeshes.add( d.mesh ) return allMeshes def getUsedJoints( filepath ): return WeightSaveData( filepath.unpickle() ).getUsedJoints() def regatherWeights( actualJointNames, weightList ): ''' re-gathers weights. when joints are re-mapped (when the original joint can't be found) there is the potential for joints to be present multiple times in the jointList - in this case, weights need to be summed for the duplicate joints otherwise maya doesn't weight the vert properly (dupes just get ignored) ''' new = {} [ new.setdefault(j, 0) for j in actualJointNames ] for j, w in zip( actualJointNames, weightList ): new[ j ] += w return new.keys(), new.values() #end
Python
from devTest import Path, TestCase from maya import cmds as cmd TEST_DIRECTORY = Path( __file__ ).up() / '_devTest_testScenes_' #location for maya files written by tests def d_makeNewScene( sceneName ): ''' simple decorator macro - will create a new scene and save it so that it exists on disk before the function is run, and gets saved once the function exits - saves having to re-write the 4 lines of code it takes to do this on every test method... ''' def decorate(f): def newF( self, *a, **kw ): cmd.file( new=True, f=True ) filename = (TEST_DIRECTORY / 'maya' / sceneName).setExtension( 'ma' ) cmd.file( rename=filename ) cmd.file( save=True ) ret = f( self, *a, **kw ) cmd.file( save=True ) return ret return newF return decorate class _BaseTest(TestCase): ''' base class for maya tests - doesn't really do anything except provide a cleanup routine that will delete all files saved to the TEST_DIRECTORY after the testCase has been run ''' _CLEANUP = True def setUp( self ): mayaDir = TEST_DIRECTORY / 'maya' mayaDir.create() def new( self ): cmd.file( new=True, f=True ) def tearDown( self ): ''' cleans out all files under the TEST_DIRECTORY folder after the tests have run ''' cmd.file( new=True, f=True ) #if the user doesn't want us to cleanup, don't! if not self._CLEANUP: return print '--- CLEANING UP TEST FILES ---' for f in TEST_DIRECTORY.files( recursive=True ): #delete the file f.delete() #end
Python
''' this script contains a bunch of useful poly mesh functionality. at this stage its not really much more than a bunch of functional scripts - there hasn't been any attempt to objectify any of this stuff yet. as it grows it may make sense to step back a bit and think about how to design this a little better ''' from maya.cmds import * from maya.OpenMayaAnim import MFnSkinCluster from vectors import Vector, Matrix from filesystem import Path, BreakException import maya.cmds as cmd import api import apiExtensions import maya.OpenMaya as OpenMaya kMAX_INF_PER_VERT = 3 kMIN_SKIN_WEIGHT_VALUE = 0.05 def getASelection(): ''' returns the first object selected or None if no selection - saves having to write this logic over and over ''' sel = ls( sl=True ) if not sel: return None return sel[0] def numVerts( mesh ): return len( cmd.ls("%s.vtx[*]" % mesh, fl=True) ) def numFaces( mesh ): return len( cmd.ls("%s.f[*]" % mesh, fl=True) ) def selectFlipped(): sel = cmd.ls(selection=True) cmd.select(clear=True) flipped = findFlipped(sel) if len(flipped): cmd.select(flipped,add=True) def findFlipped( obj ): flipped = [] faces = cmd.polyListComponentConversion( obj, toFace=True ) if not faces: return flipped faces = cmd.ls( faces, flatten=True ) for face in faces: uvNormal = getUVFaceNormal(face) #if the uv face normal is facing into screen then its flipped - add it to the list if uvNormal * Vector([0, 0, 1]) < 0: flipped.append(face) return flipped def getWindingOrder( facepath, doUvs=True ): '''will return the uvs or verts of a face in their proper 'winding order'. this can be used to determine things like uv face normals and... well, pretty much that''' toReturn = [] vtxFaces = cmd.ls(cmd.polyListComponentConversion(facepath,toVertexFace=True),flatten=True) for vtxFace in vtxFaces: if doUvs: uvs = cmd.polyListComponentConversion(vtxFace,fromVertexFace=True,toUV=True) toReturn.append( uvs[0] ) else: vtx = cmd.polyListComponentConversion(vtxFace,fromVertexFace=True,toVertex=True) toReturn.append( vtx[0] ) return toReturn def getUVFaceNormal( facepath ): uvs = getWindingOrder(facepath) if len(uvs) < 3: return (1,0,0) #if there are less than 3 uvs we have no uv area so bail #get edge vectors and cross them to get the uv face normal uvAPos = cmd.polyEditUV(uvs[0], query=True, uValue=True, vValue=True) uvBPos = cmd.polyEditUV(uvs[1], query=True, uValue=True, vValue=True) uvCPos = cmd.polyEditUV(uvs[2], query=True, uValue=True, vValue=True) uvAB = Vector( [uvBPos[0]-uvAPos[0], uvBPos[1]-uvAPos[1], 0] ) uvBC = Vector( [uvCPos[0]-uvBPos[0], uvCPos[1]-uvBPos[1], 0] ) uvNormal = uvAB.cross( uvBC ).normalize() return uvNormal def getFaceNormal( facepath ): verts = getWindingOrder(facepath,False) if len(verts) < 3: return (1, 0, 0) #if there are less than 3 verts we have no uv area so bail #get edge vectors and cross them to get the uv face normal vertAPos = Vector(cmd.xform(verts[0], query=True, worldSpace=True, absolute=True, translation=True)) vertBPos = Vector(cmd.xform(verts[1], query=True, worldSpace=True, absolute=True, translation=True)) vertCPos = Vector(cmd.xform(verts[2], query=True, worldSpace=True, absolute=True, translation=True)) vecAB = vertBPos - vertAPos vecBC = vertCPos - vertBPos faceNormal = (vecAB ^ vecBC).normalize() return faceNormal def extractFaces( faceList, delete=False ): ''' extracts the given faces into a separate object - unlike the maya function, this is actually useful... the given faces are extracted to a separate object, and can be optionally deleted from the original mesh if desired, or just duplicated out. ''' newMeshes = [] #get a list of meshes present in the facelist cDict = componentListToDict( faceList ) for mesh, faces in cDict.iteritems(): #is the mesh a shape or a transform - if its a shape, get its transform if cmd.nodeType( mesh ) == 'mesh': mesh = cmd.listRelatives( mesh, pa=True, p=True )[ 0 ] dupeMesh = cmd.duplicate( mesh, renameChildren=True )[ 0 ] children = cmd.listRelatives( dupeMesh, pa=True, typ='transform' ) if children: cmd.delete( children ) #unlock transform channels - if possible anyway try: for c in ('t', 'r', 's'): setAttr( '%s.%s' % (dupeMesh, c), l=False ) for ax in ('x', 'y', 'z'): setAttr( '%s.%s%s' % (dupeMesh, c, ax), l=False ) except RuntimeError: pass #now delete all faces except those we want to keep cmd.select( [ '%s.f[%d]' % (dupeMesh, idx) for idx in range( numFaces( dupeMesh ) ) ] ) cmd.select( [ '%s.f[%d]' % (dupeMesh, idx) for idx in faces ], deselect=True ) cmd.delete() newMeshes.append( dupeMesh ) if delete: cmd.delete( faceList ) return newMeshes def extractMeshForEachJoint( joints, tolerance=1e-4 ): extractedMeshes = [] for j in joints: meshes = extractFaces( jointFacesForMaya( j, tolerance ) ) extractedMeshes += meshes for m in meshes: #unlock all xform attrs for at in 't', 'r', 's': cmd.setAttr( '%s.%s' % (m, at), l=False ) for ax in 'x', 'y', 'z': cmd.setAttr( '%s.%s%s' % (m, at, ax), l=False ) cmd.parent( m, j ) args = cmd.xform( j, q=True, ws=True, rp=True ) + [ '%s.rotatePivot' % m, '%s.scalePivot' % m ] cmd.move( *args ) cmd.makeIdentity( m, a=True, t=True, r=True, s=True ) cmd.parent( m, world=True ) return extractedMeshes def extractMeshForJoints( joints, tolerance=0.25, expand=0 ): ''' given a list of joints this will extract the mesh influenced by these joints into a separate object. the default tolerance is high because verts are converted to faces which generally results in a larger than expected set of faces ''' faces = [] joints = map( str, joints ) for j in joints: faces += jointFacesForMaya( j, tolerance, False ) if not faces: return None theJoint = joints[ 0 ] meshes = extractFaces( faces ) grp = cmd.group( em=True, name='%s_mesh#' % theJoint ) cmd.delete( cmd.parentConstraint( theJoint, grp ) ) for m in meshes: #unlock all xform attrs for at in 't', 'r', 's': cmd.setAttr( '%s.%s' % (m, at), l=False ) for ax in 'x', 'y', 'z': cmd.setAttr( '%s.%s%s' % (m, at, ax), l=False ) if expand > 0: cmd.polyMoveFacet( "%s.vtx[*]" % m, ch=False, ltz=expand ) #parent to the grp and freeze transforms to ensure the shape's space is the same as its new parent cmd.parent( m, grp ) cmd.makeIdentity( m, a=True, t=True, r=True, s=True ) #parent all shapes to the grp cmd.parent( cmd.listRelatives( m, s=True, pa=True ), grp, add=True, s=True ) #delete the mesh transform cmd.delete( m ) #remove any intermediate objects... for shape in listRelatives( grp, s=True, pa=True ): if getAttr( '%s.intermediateObject' % shape ): delete( shape ) return grp def autoGenerateRagdollForEachJoint( joints, threshold=0.65 ): convexifiedMeshes = [] for j in joints: meshes = extractMeshForEachJoint( [ j ], threshold ) if len( meshes ) > 1: mesh = cmd.polyUnite( meshes, ch=False )[ 0 ] cmd.delete( meshes ) meshes = [ mesh ] else: mesh = meshes[ 0 ] convexifiedMesh = convexifyObjects( mesh )[ 0 ] convexifiedMesh = cmd.rename( convexifiedMesh, j +'_ragdoll' ) cmd.skinCluster( [ j ], convexifiedMesh ) cmd.delete( meshes ) convexifiedMeshes.append( convexifiedMesh ) return convexifiedMeshes def isPointInCube( point, volumePos, volumeScale, volumeBasis ): ''' ''' x, y, z = volumeScale #make the point's position relative to the volume, and transform it to the volume's local orientation pointRel = point - volumePos pointRel = pointRel.change_space( *volumeBasis ) if -x<= pointRel.x <=x and -y<= pointRel.y <=y and -z<= pointRel.z <=z: acc = 0 for x, px in zip((x, y, z), (point.x, point.y, point.z)): try: acc += x/px except ZeroDivisionError: acc += 1 weight = 1 -(acc/3) return True, weight return False def isPointInSphere( point, volumePos, volumeScale, volumeBasis ): ''' returns whether a given point is contained within a scaled sphere ''' x, y, z = volumeScale #make the point's position relative to the volume, and transform it to the volume's local orientation pointRel = point - volumePos pointRel = pointRel.change_space(*volumeBasis) if -x<= pointRel.x <=x and -y<= pointRel.y <=y and -z<= pointRel.z <=z: pointN = vectors.Vector(pointRel) pointN.x /= x pointN.y /= y pointN.z /= z pointN = pointN.normalize() pointN.x *= x pointN.y *= y pointN.z *= z if pointRel.magnitude() <= pointN.mag: weight = 1 -(pointRel.magnitude() / pointN.magnitude()) return True, weight return False def isPointInUniformSphere( point, volumePos, volumeRadius, UNUSED_BASIS=None ): pointRel = point - volumePos radius = volumeRadius[0] if -radius<= pointRel.x <=radius and -radius<= pointRel.y <=radius and -radius<= pointRel.z <=radius: if pointRel.magnitude() <= radius: weight = 1 -(pointRel.magnitude() / radius) return True, weight return False def findFacesInVolumeForMaya( meshes, volume, contained=False ): ''' does the conversion from useful dict to maya selection string - generally only useful to mel trying to interface with this functionality ''' objFacesDict = findFacesInVolume(meshes, volume, contained) allFaces = [] for mesh, faces in objFacesDict.iteritems(): allFaces.extend( ['%s.%s' % (mesh, f) for f in faces] ) return allFaces def findVertsInVolumeForMaya( meshes, volume ): ''' does the conversion from useful dict to maya selection string - generally only useful to mel trying to interface with this functionality ''' objVertDict = findVertsInVolume(meshes, volume) allVerts = [] for mesh, verts in objVertDict.iteritems(): allVerts.extend( ['%s.vtx[%s]' % (mesh, v.id) for v in verts] ) return allVerts def findFacesInVolume( meshes, volume, contained=False ): ''' returns a dict containing the of faces within a given volume. if contained is True, then only faces wholly contained by the volume are returned ''' meshVertsWithin = findVertsInVolume(meshes, volume) meshFacesWithin = {} for mesh,verts in meshVertsWithin.iteritems(): if not verts: continue meshFacesWithin[mesh] = [] vertNames = ['%s.vtx[%d]' % (mesh, v.id) for v in verts] if contained: faces = set(cmd.ls(cmd.polyListComponentConversion(vertNames, toFace=True), fl=True)) [faces.remove(f) for f in cmd.ls(cmd.polyListComponentConversion(vertNames, toFace=True, border=True), fl=True)] meshFacesWithin[mesh] = [f.split('.')[1] for f in faces] else: faces = cmd.ls(cmd.polyListComponentConversion(vertNames, toFace=True), fl=True) meshFacesWithin[mesh] = [f.split('.')[1] for f in faces] return meshFacesWithin def findVertsInVolume( meshes, volume ): ''' returns a dict containing meshes and the list of vert attributes contained within the given <volume> ''' #define a super simple vector class to additionally record vert id with position... class VertPos(vectors.Vector): def __init__( self, x, y, z, vertIdx=None ): vectors.Vector.__init__(self, [x, y, z]) self.id = vertIdx #this dict provides the functions used to determine whether a point is inside a volume or not insideDeterminationMethod = {ExportManager.kVOLUME_SPHERE: isPointInSphere, ExportManager.kVOLUME_CUBE: isPointInCube} #if there are any uniform overrides for the contained method (called if the volume's scale is #unity) it can be registered here insideDeterminationIfUniform = {ExportManager.kVOLUME_SPHERE: isPointInUniformSphere, ExportManager.kVOLUME_CUBE: isPointInCube} #grab any data we're interested in for the volume volumePos = vectors.Vector( cmd.xform(volume, q=True, ws=True, rp=True) ) volumeScale = map(abs, cmd.getAttr('%s.s' % volume)[0]) volumeBasis = rigUtils.getObjectBasisVectors( volume ) #make sure the basis is normalized volumeBasis = [v.normalize() for v in volumeBasis] #now lets determine the volume type type = ExportManager.kVOLUME_SPHERE try: type = int( cmd.getAttr('%s.exportVolume' % volume) ) except TypeError: pass isContainedMethod = insideDeterminationMethod[type] print 'method for interior volume determination', isContainedMethod.__name__ sx = volumeScale[0] if vectors.Vector(volumeScale).within((sx, sx, sx)): try: isContainedMethod = insideDeterminationIfUniform[type] except KeyError: pass #now lets iterate over the geometry meshVertsWithin = {} for mesh in meshes: #its possible to pass not a mesh but a component in - this is totally valid, as the polyListComponentConversion #should make sure we're always dealing with verts no matter what, but we still need to make sure the dict key is #the actual name of the mesh - hence this bit of jiggery pokery dotIdx = mesh.rfind('.') meshName = mesh if dotIdx == -1 else mesh[:dotIdx] meshPositions = [] meshVertsWithin[meshName] = meshPositions #this gives us a huge list of floats - each sequential triple is the position of a vert try: #if this complains its most likely coz the geo is bad - so skip it... vertPosList = cmd.xform(cmd.ls(cmd.polyListComponentConversion(mesh, toVertex=True), fl=True), q=True, t=True, ws=True) except TypeError: continue count = len(vertPosList)/3 for idx in xrange(count): pos = VertPos(vertPosList.pop(0), vertPosList.pop(0), vertPosList.pop(0), idx) contained = isContainedMethod(pos, volumePos, volumeScale, volumeBasis) if contained: pos.weight = contained[1] meshPositions.append( pos ) return meshVertsWithin def isNodeVisible( node ): ''' its actually a bit tricky to determine whether a node is visible or not. A node is hidden if any parent is hidden by either having a zero visibility attribute. It could also be in a layer or be parented to a node in a layer that is turned off... This function will sort all that crap out and return a bool representing the visibility of the given node ''' def isVisible( n ): #obvious check first if not getAttr( '%s.v' % node ): return False #now check the layer displayLayer = listConnections( '%s.drawOverride' % n, d=False, type='displayLayer' ) if displayLayer: if not getAttr( '%s.v' % displayLayer[0] ): return False return True #check the given node if not isVisible( node ): return False #now walk up the DAG and check visibility on parents parent = listRelatives( node, p=True, pa=True ) while parent: if not isVisible( parent[0] ): return False parent = listRelatives( parent, p=True, pa=True ) return True def jointVerts( joint, tolerance=1e-4, onlyVisibleMeshes=True ): ''' returns a dict containing data about the verts influences by the given joint - dict keys are mesh names the joint affects. each dict value is a list of tuples containing (weight, idx) for the verts affected by the joint ''' newObjs = [] meshVerts = {} joint = apiExtensions.asMObject( joint ) jointMDag = joint.dagPath() try: skins = list( set( listConnections( joint, s=0, type='skinCluster' ) ) ) except TypeError: return meshVerts MObject = OpenMaya.MObject MDagPath = OpenMaya.MDagPath MDoubleArray = OpenMaya.MDoubleArray MSelectionList = OpenMaya.MSelectionList MIntArray = OpenMaya.MIntArray MFnSingleIndexedComponent = OpenMaya.MFnSingleIndexedComponent for skin in skins: skin = apiExtensions.asMObject( skin ) mfnSkin = MFnSkinCluster( skin ) mSel = MSelectionList() mWeights = MDoubleArray() mfnSkin.getPointsAffectedByInfluence( jointMDag, mSel, mWeights ) for n in range( mSel.length() ): mesh = MDagPath() component = MObject() mSel.getDagPath( n, mesh, component ) #if we only want visible meshes - check to see that this mesh is visible if onlyVisibleMeshes: if not isNodeVisible( mesh ): continue c = MFnSingleIndexedComponent( component ) idxs = MIntArray() c.getElements( idxs ) meshVerts[ mesh.partialPathName() ] = [ (w, idx) for idx, w in zip( idxs, mWeights ) if w > tolerance ] return meshVerts def jointVertsForMaya( joint, tolerance=1e-4, onlyVisibleMeshes=True ): ''' converts the dict returned by jointVerts into maya useable component names ''' items = [] for mesh, data in jointVerts( joint, tolerance, onlyVisibleMeshes ).iteritems(): items.extend( ['%s.vtx[%d]' % (mesh, n) for w, n in data] ) return items def jointFacesForMaya( joint, tolerance=1e-4, contained=True ): ''' returns a list containing the faces influences by the given joint ''' verts = jointVertsForMaya( joint, tolerance ) if not verts: return [] if contained: faceList = cmd.polyListComponentConversion( verts, toFace=True ) if faceList: faceList = set( cmd.ls( faceList, fl=True ) ) for f in cmd.ls( cmd.polyListComponentConversion( verts, toFace=True, border=True ), fl=True ): faceList.remove( f ) jointFaces = list( faceList ) else: jointFaces = cmd.ls( cmd.polyListComponentConversion( verts, toFace=True ), fl=True ) return jointFaces def jointFaces( joint, tolerance=1e-4, contained=True ): ''' takes the list of maya component names from jointFacesForMaya and converts them to a dict with teh same format as jointVerts(). this is backwards for faces simply because its based on grabbing the verts, and transforming them to faces, and then back to a dict... ''' return componentListToDict( jointFacesForMaya( joint, tolerance, contained ) ) def componentListToDict( componentList ): componentDict = {} if not componentList: return componentDict #detect the prefix type suffix = componentList[ 0 ].split( '.' )[ 1 ] componentPrefix = suffix[ :suffix.find( '[' ) ] prefixLen = len( componentPrefix ) + 1 #add one because there is always a "[" after the component str for face in componentList: mesh, idStr = face.split( '.' ) idx = int( idStr[ prefixLen:-1 ] ) try: componentDict[ mesh ].append( idx ) except KeyError: componentDict[ mesh ] = [ idx ] return componentDict def stampVolumeToJoint( joint, volume, amount=0.1 ): meshes = cmd.ls(cmd.listHistory(joint, f=True, interestLevel=2), type='mesh') assert meshes jointPos = Vector(cmd.xform(joint, q=True, ws=True, rp=True)) vertsDict = findVertsInVolume(meshes, volume) for mesh, verts in vertsDict.iteritems(): skinCluster = cmd.ls(cmd.listHistory(mesh), type='skinCluster')[0] for vert in verts: vertName = '%s.vtx[%s]' % (mesh, vert.id) weight = vert.weight #print weight, vertName #print cmd.skinPercent(skinCluster, vertName, q=True, t=joint, v=True) currentWeight = cmd.skinPercent(skinCluster, vertName, q=True, t=joint, v=True) currentWeight += weight * amount #cmd.skinPercent(skinCluster, vertName, t=joint, v=currentWeight) print vertName, currentWeight @api.d_progress(t='clamping influence count', st='clamping vert influences to %d' % kMAX_INF_PER_VERT) def clampVertInfluenceCount( geos=None ): ''' ''' global kMAX_INF_PER_VERT, kMIN_SKIN_WEIGHT_VALUE progressWindow = cmd.progressWindow skinPercent = cmd.skinPercent halfMin = kMIN_SKIN_WEIGHT_VALUE / 2.0 if geos is None: geos = cmd.ls(sl=True) for geo in geos: skin = cmd.ls(cmd.listHistory(geo), type='skinCluster')[0] verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True) inc = 100.0 / len( verts ) progress = 0 vertsFixed = [] for vert in verts: progress += inc progressWindow(e=True, progress=progress) reapplyWeights = False weightList = skinPercent(skin, vert, ib=1e-5, q=True, value=True) if len(weightList) > kMAX_INF_PER_VERT: jointList = skinPercent(skin, vert, ib=halfMin, q=True, transform=None) sorted = zip(weightList, jointList) sorted.sort() #now clamp to the highest kMAX_INF_PER_VERT number of weights, and re-normalize sorted = sorted[ -kMAX_INF_PER_VERT: ] weightSum = sum( [ a for a, b in sorted ] ) t_values = [ (b, a/weightSum) for a, b in sorted ] reapplyWeights = True else: for n, v in enumerate( weightList ): if v <= kMIN_SKIN_WEIGHT_VALUE: jointList = skinPercent( skin, vert, ib=halfMin, q=True, transform=None ) t_values = [ (a, b) for a, b in zip( jointList, weightList ) if b > halfMin ] reapplyWeights = True break if reapplyWeights: js = [ a for a, b in t_values ] vs = renormalizeWithMinimumValue( [ b for a, b in t_values ] ) t_values = zip( js, vs ) skinPercent( skin, vert, tv=t_values ) vertsFixed.append( vert ) #turn on limiting in the skinCluster cmd.setAttr('%s.maxInfluences' % skin, kMAX_INF_PER_VERT) cmd.setAttr('%s.maintainMaxInfluences' % skin, 1) print 'fixed skin weights on %d verts' % len( vertsFixed ) #print '\n'.join( vertsFixed ) def renormalizeWithMinimumValue( values, minValue=kMIN_SKIN_WEIGHT_VALUE ): minCount = sum( 1 for v in values if v <= minValue ) toAlter = [ n for n, v in enumerate( values ) if v > minValue ] modValues = [ max( minValue, v ) for v in values ] toAlterSum = sum( [ values[ n ] for n in toAlter ] ) for n in toAlter: modValues[ n ] /= toAlterSum modifier = 1.0035 + ( float( minCount ) * minValue ) for n in toAlter: modValues[ n ] /= modifier return modValues def getBoundsForJoint( joint ): ''' returns bounding box data (as a 6-tuple: xmin, xmax, ymin etc...) for the geometry influenced by a given joint ''' verts = jointVertsForMaya(joint, 0.01) Xs, Ys, Zs = [], [], [] for v in verts: x, y, z = cmd.xform(v, q=True, ws=True, t=True) Xs.append(x) Ys.append(y) Zs.append(z) Xs.sort() Ys.sort() Zs.sort() try: return Xs[0], Xs[-1], Ys[0], Ys[-1], Zs[0], Zs[-1] except IndexError: drawSize = cmd.getAttr('%s.radius' % joint) drawSize /= 2 return -drawSize, drawSize, -drawSize, drawSize, -drawSize, drawSize def getAlignedBoundsForJoint( joint, threshold=0.65, onlyVisibleMeshes=True ): ''' looks at the verts the given joint/s and determines a local space (local to the first joint in the list if multiple are given) bounding box of the verts, and positions the hitbox accordingly if onlyVisibleMeshes is True, then only meshes that are visible in the viewport will contribute to the bounds ''' theJoint = joint verts = [] #so this is just to deal with the input arg being a tuple, list or string. you can pass in a list #of joint names and the verts affected just get accumulated into a list, and the resulting bound #should be the inclusive bounding box for the given joints if isinstance( joint, (tuple,list) ): theJoint = joint[0] for joint in joint: verts += jointVertsForMaya( joint, threshold, onlyVisibleMeshes ) else: verts += jointVertsForMaya( joint, threshold, onlyVisibleMeshes ) jointDag = api.getMDagPath( theJoint ) jointMatrix = jointDag.inclusiveMatrix() vJointPos = OpenMaya.MTransformationMatrix( jointMatrix ).rotatePivot( OpenMaya.MSpace.kWorld ) + OpenMaya.MTransformationMatrix( jointMatrix ).getTranslation( OpenMaya.MSpace.kWorld ) vJointPos = Vector( [vJointPos.x, vJointPos.y, vJointPos.z] ) vJointBasisX = OpenMaya.MVector(-1,0,0) * jointMatrix vJointBasisY = OpenMaya.MVector(0,-1,0) * jointMatrix vJointBasisZ = OpenMaya.MVector(0,0,-1) * jointMatrix bbox = OpenMaya.MBoundingBox() for vert in verts: #get the position relative to the joint in question vPos = Vector( xform(vert, query=True, ws=True, t=True) ) vPos = vJointPos - vPos #now transform the joint relative position into the coordinate space of that joint #we do this so we can get the width, height and depth of the bounds of the verts #in the space oriented along the joint vPosInJointSpace = Vector( (vPos.x, vPos.y, vPos.z) ) vPosInJointSpace = vPosInJointSpace.change_space( vJointBasisX, vJointBasisY, vJointBasisZ ) bbox.expand( OpenMaya.MPoint( *vPosInJointSpace ) ) minB, maxB = bbox.min(), bbox.max() return minB[0], minB[1], minB[2], maxB[0], maxB[1], maxB[2] def getJointScale( joint ): ''' basically just returns the average bounding box side length... is useful to use as an approximation for a joint's "size" ''' xmn, xmx, ymn, ymx, zmn, zmx = getBoundsForJoint(joint) x = xmx - xmn y = ymx - ymn z = zmx - zmn return (x + y + z) / 3 #end
Python
''' super simple vector class and vector functionality. i wrote this simply because i couldn't find anything that was easily accessible and quick to write. this may just go away if something more comprehensive/mature is found ''' import re import math import random from math import cos, sin, tan, acos, asin, atan2 sqrt = math.sqrt zeroThreshold = 1e-8 class MatrixException(Exception): pass class Angle(object): def __init__( self, angle, radian=False ): '''set the radian to true on init if the angle is in radians - otherwise degrees are assumed''' if radian: self.radians = angle self.degrees = math.degrees(angle) else: self.degrees = angle self.radians = math.radians(angle) class Vector(list): ''' provides a bunch of common vector functionality. Vectors must be instantiated a list/tuple of values. If you need to instantiate with items, use the Vector.FromValues like so: Vector.FromValues(1,2,3) ''' @classmethod def FromValues( cls, *a ): return cls( a ) def __repr__( self ): return '%s( %s )' % (type( self ).__name__, tuple( self )) def __str__( self ): return '<%s>' % ', '.join( '%0.3g' % v for v in self ) def setIndex( self, idx, value ): self[ idx ] = value def __nonzero__( self ): for item in self: if item: return True return False def __add__( self, other ): return self.__class__( [x+y for x, y in zip(self, other)] ) __iadd__ = __add__ def __radd__( self, other ): return self.__class__( [x+y for x, y in zip(other, self)] ) def __sub__( self, other ): return self.__class__( [x-y for x,y in zip(self, other)] ) def __mul__( self, factor ): ''' supports either scalar multiplication, or vector multiplication (dot product). for cross product use the .cross( other ) method which is bound to the rxor operator. ie: a ^ b == a.cross( b ) ''' if isinstance( factor, (int, float) ): return self.__class__( [x * factor for x in self] ) elif isinstance( factor, Matrix ): return multVectorMatrix( self, factor ) #assume its another vector then value = self[0] * factor[0] for x, y in zip( self[1:], factor[1:] ): value += x*y return value def __div__( self, denominator ): return self.__class__( [x / denominator for x in self] ) def __neg__( self ): return self.__class__( [-x for x in self] ) __invert__ = __neg__ def __eq__( self, other, tolerance=1e-5 ): ''' overrides equality test - can specify a tolerance if called directly. NOTE: other can be any iterable ''' for a, b in zip(self, other): if abs( a - b ) > tolerance: return False return True within = __eq__ def __ne__( self, other, tolerance=1e-5 ): return not self.__eq__( other, tolerance ) def __mod__( self, other ): return self.__class__( [x % other for x in self] ) def __int__( self ): return int( self.get_magnitude() ) def __hash__( self ): return hash( tuple( self ) ) @classmethod def Zero( cls, size=3 ): return cls( ([0] * size) ) @classmethod def Random( cls, size=3, valueRange=(0,1) ): return cls( [random.uniform( *valueRange ) for n in range( size )] ) @classmethod def Axis( cls, axisName, size=3 ): ''' returns a vector from an axis name - the axis name can be anything from the Vector.INDEX_NAMES list. you can also use a - sign in front of the axis name ''' axisName = axisName.lower() isNegative = axisName.startswith('-') or axisName.startswith('_') if isNegative: axisName = axisName[1:] new = cls.Zero( size ) val = 1 if isNegative: val = -1 new.__setattr__( axisName, val ) return new def dot( self, other, preNormalize=False ): a, b = self, other if preNormalize: a = self.normalize() b = other.normalize() dot = sum( [x*y for x,y in zip(a, b)] ) return dot def __rxor__( self, other ): ''' used for cross product - called using a**b NOTE: the cross product is only defined for a 3 vector ''' x = self[1] * other[2] - self[2] * other[1] y = self[2] * other[0] - self[0] * other[2] z = self[0] * other[1] - self[1] * other[0] return self.__class__( [x, y, z] ) cross = __rxor__ def get_squared_magnitude( self ): ''' returns the square of the magnitude - which is about 20% faster to calculate ''' m = 0 for val in self: m += val**2 return m def get_magnitude( self ): #NOTE: this implementation is faster than sqrt( sum( [x**2 for x in self] ) ) by about 20% m = 0 for val in self: m += val**2 return sqrt( m ) __float__ = get_magnitude __abs__ = get_magnitude length = magnitude = get_magnitude def set_magnitude( self, factor ): ''' changes the magnitude of this instance ''' factor /= self.get_magnitude() for n in range( len( self ) ): self[n] *= factor def normalize( self ): ''' returns a normalized vector ''' #inline the code for the SPEEDZ - its about 8% faster by inlining the code to calculate the magnitude mag = 0 for v in self: mag += v**2 mag = sqrt( mag ) return self.__class__( [v / mag for v in self] ) def change_space( self, basisX, basisY, basisZ=None ): ''' will re-parameterize this vector to a different space NOTE: the basisZ is optional - if not given, then it will be computed from X and Y NOTE: changing space isn't supported for 4-vectors ''' if basisZ is None: basisZ = basisX ^ basisY basisZ = basisZ.normalize() dot = self.dot new = dot( basisX ), dot( basisY ), dot( basisZ ) return self.__class__( new ) def rotate( self, quat ): ''' Return the rotated vector v. The quaternion must be a unit quaternion. This operation is equivalent to turning v into a quat, computing self*v*self.conjugate() and turning the result back into a vec3. ''' ww = quat.w * quat.w xx = quat.x * quat.x yy = quat.y * quat.y zz = quat.z * quat.z wx = quat.w * quat.x wy = quat.w * quat.y wz = quat.w * quat.z xy = quat.x * quat.y xz = quat.x * quat.z yz = quat.y * quat.z newX = ww * self.x + xx * self.x - yy * self.x - zz * self.x + 2*((xy-wz) * self.y + (xz+wy) * self.z) newY = ww * self.y - xx * self.y + yy * self.y - zz * self.y + 2*((xy+wz) * self.x + (yz-wx) * self.z) newZ = ww * self.z - xx * self.z - yy * self.z + zz * self.z + 2*((xz-wy) * self.x + (yz+wx) * self.y) return self.__class__( [newX, newY, newZ] ) def complex( self ): return self.__class__( [ complex(v) for v in tuple(self) ] ) def conjugate( self ): return self.__class__( [ v.conjugate() for v in tuple(self.complex()) ] ) x = property( lambda self: self[ 0 ], lambda self, value: self.setIndex( 0, value ) ) y = property( lambda self: self[ 1 ], lambda self, value: self.setIndex( 1, value ) ) z = property( lambda self: self[ 2 ], lambda self, value: self.setIndex( 2, value ) ) w = property( lambda self: self[ 3 ], lambda self, value: self.setIndex( 3, value ) ) class Point(Vector): def __init__( self, vals ): if isinstance( vals, Point ): list.__init__( self, vals ) return selfLen = len( self ) if selfLen == 3: vals.append( 1 ) else: assert selfLen == 4 list.__init__( vals ) class Colour(Vector): NAMED_PRESETS = { "active": (0.26, 1, 0.64), "black": (0, 0, 0), "white": (1, 1, 1), "grey": (.5, .5, .5), "lightgrey": (.7, .7, .7), "darkgrey": (.25, .25, .25), "red": (1, 0, 0), "lightred": (1, .5, 1), "peach": (1, .5, .5), "darkred": (.6, 0, 0), "orange": (1., .5, 0), "lightorange": (1, .7, .1), "darkorange": (.7, .25, 0), "yellow": (1, 1, 0), "lightyellow": (1, 1, .5), "darkyellow": (.8,.8,0.), "green": (0, 1, 0), "lightgreen": (.4, 1, .2), "darkgreen": (0, .5, 0), "blue": (0, 0, 1), "lightblue": (.4, .55, 1), "darkblue": (0, 0, .4), "purple": (.7, 0, 1), "lightpurple": (.8, .5, 1), "darkpurple": (.375, 0, .5), "brown": (.57, .49, .39), "lightbrown": (.76, .64, .5), "darkbrown": (.37, .28, .17) } NAMED_PRESETS[ 'highlight' ] = NAMED_PRESETS[ 'active' ] NAMED_PRESETS[ 'pink' ] = NAMED_PRESETS[ 'lightred' ] DEFAULT_COLOUR = NAMED_PRESETS[ 'black' ] DEFAULT_ALPHA = 0.7 #alpha=0 is opaque, alpha=1 is transparent INDEX_NAMES = 'rgba' _EQ_TOLERANCE = 0.1 _NUM_RE = re.compile( '^[0-9. ]+' ) def __eq__( self, other, tolerance=_EQ_TOLERANCE ): return Vector.__eq__( self, other, tolerance ) def __ne__( self, other, tolerance=_EQ_TOLERANCE ): return Vector.__ne__( self, other, tolerance ) def __init__( self, colour ): ''' colour can be a combination: name alpha -> darkred 0.5 name r g b a -> 1 0 0 0.2 if r, g, b or a are missing, they're assumed to be 0 a 4 float, RGBA array is returned ''' if isinstance( colour, basestring ): alpha = self.DEFAULT_ALPHA toks = colour.lower().split( ' ' )[ :4 ] if len( toks ) > 1: if toks[ -1 ].isdigit(): alpha = float( toks[ -1 ] ) clr = [0,0,0,alpha] for n, c in enumerate( self.DEFAULT_COLOUR[ :4 ] ): clr[ n ] = c clr[ 3 ] = alpha if not toks[ 0 ].isdigit(): try: clr = list( self.NAMED_PRESETS[ toks[ 0 ] ] )[ :3 ] clr.append( alpha ) except KeyError: pass else: for n, t in enumerate( toks ): try: clr[ n ] = float( t ) except ValueError: continue else: clr = colour Vector.__init__( self, clr ) def darken( self, factor ): ''' returns a colour vector that has been darkened by the appropriate ratio. this is basically just a multiply, but the alpha is unaffected ''' darkened = self * factor darkened[ 3 ] = self[ 3 ] return darkened def lighten( self, factor ): toWhiteDelta = Colour( (1,1,1,0) ) - self toWhiteDelta = toWhiteDelta * factor lightened = self + toWhiteDelta lightened[ 3 ] = self[ 3 ] return lightened def asRGB( self ): return list( self )[ :3 ] @classmethod def ColourToName( cls, theColour ): ''' given an arbitrary colour, will return the most appropriate name as defined in the NAMED_PRESETS class dict ''' if not isinstance( theColour, Colour ): theColour = Colour( theColour ) theColour = Vector( theColour[ :3 ] ) #make sure its a 3 vector matches = [] for name, colour in cls.NAMED_PRESETS.iteritems(): colour = Vector( colour ) diff = (colour - theColour).magnitude() matches.append( (diff, name) ) matches.sort() return matches[ 0 ][ 1 ] Color = Colour #for spelling n00bs class Axis(int): BASE_AXES = 'x', 'y', 'z' AXES = ( 'x', 'y', 'z', \ '-x', '-y', '-z' ) def __new__( cls, idx ): if isinstance( idx, basestring ): return cls.FromName( idx ) return int.__new__( cls, idx % 6 ) def __neg__( self ): return Axis( (self + 3) ) def __abs__( self ): return type( self )( self % 3 ) positive = __abs__ @classmethod def FromName( cls, name ): idx = list( cls.AXES ).index( name.lower().replace( '_', '-' ) ) return cls( idx ) @classmethod def FromVector( cls, vector ): ''' returns the closest axis to the given vector ''' assert len( cls.BASE_AXES ) >= len( vector ) listV = list( vector ) idx, value = 0, listV[ 0 ] for n, v in enumerate( listV ): if v > value: value = v idx = n return cls( idx ) def asVector( self ): v = Vector( [0, 0, 0] ) v[ self % 3 ] = 1 if self < 3 else -1 return v def isNegative( self ): return self > 2 def asName( self ): return self.AXES[ self ] def asCleanName( self ): ''' returns the axis name without a negative regardless ''' return self.AXES[ self ].replace( '-', '' ) def asEncodedName( self ): ''' returns the axis name, replacing the - with an _ ''' return self.asName().replace( '-', '_' ) def otherAxes( self ): ''' returns the other two axes that aren't this axis ''' allAxes = [ 0, 1, 2 ] allAxes.remove( self % 3 ) return list( map( Axis, allAxes ) ) AX_X, AX_Y, AX_Z = map( Axis, range( 3 ) ) """ class EulerRotation(Vector): def __init__( self, vals, degrees=True ): pass def radians( self ): return list( self ) def degrees( self ): return list( map( math.degrees, self ) ) """ class Quaternion(Vector): def __init__( self, xyzw=(0,0,0,1) ): ''' initialises a vector from either x,y,z,w args or a Matrix instance ''' if isinstance(xyzw, Matrix): #the matrix is assumed to be a valid rotation matrix matrix = x d1, d2, d3 = matrix.getDiag() t = d1 + d2 + d3 + 1.0 if t > zeroThreshold: s = 0.5 / sqrt( t ) w = 0.25 / s x = ( matrix[2][1] - matrix[1][2] )*s y = ( matrix[0][2] - matrix[2][0] )*s z = ( matrix[1][0] - matrix[0][1] )*s else: if d1 >= d2 and d1 >= d3: s = sqrt( 1.0 + d1 - d2 - d3 ) * 2.0 x = 0.5 / s y = ( matrix[0][1] + matrix[1][0] )/s z = ( matrix[0][2] + matrix[2][0] )/s w = ( matrix[1][2] + matrix[2][1] )/s elif d2 >= d1 and d2 >= d3: s = sqrt( 1.0 + d2 - d1 - d3 ) * 2.0 x = ( matrix[0][1] + matrix[1][0] )/s y = 0.5 / s z = ( matrix[1][2] + matrix[2][1] )/s w = ( matrix[0][2] + matrix[2][0] )/s else: s = sqrt( 1.0 + d3 - d1 - d2 ) * 2.0 x = ( matrix[0][2] + matrix[2][0] )/s y = ( matrix[1][2] + matrix[2][1] )/s z = 0.5 / s w = ( matrix[0][1] + matrix[1][0] )/s xyzw = x, y, z, w Vector.__init__( self, xyzw ) def __mul__( self, other ): if isinstance( other, Quaternion ): x1, y1, z1, w1 = self x2, y2, z2, w2 = other newW = w1*w2 - x1*x2 - y1*y2 - z1*z2 newX = w1*x2 + x1*w2 + y1*z2 - z1*y2 newY = w1*y2 - x1*z2 + y1*w2 + z1*x2 newZ = w1*z2 + x1*y2 - y1*x2 + z1*w2 return self.__class__( [newX, newY, newZ, newW] ) elif isinstance( other, (float, int, long) ): return self.__class__( [i * other for i in self] ) __rmul__ = __mul__ def __div__( self, other ): assert isinstance( other, (float, int, long) ) return self.__class__( [i / other for i in self] ) def copy( self ): return self.__class__(self) @classmethod def FromEulerXYZ( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerXYZ(x, y, z, degrees)) @classmethod def FromEulerYZX( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerYZX(x, y, z, degrees)) @classmethod def FromEulerZXY( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerZXY(x, y, z, degrees)) @classmethod def FromEulerXZY( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerXZY(x, y, z, degrees)) @classmethod def FromEulerYXZ( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerYXZ(x, y, z, degrees)) @classmethod def FromEulerZYX( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerZYX(x, y, z, degrees)) @classmethod def AxisAngle( cls, axis, angle, normalize=False ): '''angle is assumed to be in radians''' if normalize: axis = axis.normalize() angle /= 2.0 newW = cos( angle ) x, y, z = axis s = sin( angle ) / sqrt( x**2 + y**2 + z**2 ) newX = x * s newY = y * s newZ = z * s new = cls( [newX, newY, newZ, newW] ) new = new.normalize() return new def toAngleAxis( self ): '''Return angle (in radians) and rotation axis. ''' nself = self.normalize() # Clamp nself.w (since the quat has to be normalized it should # be between -1 and 1 anyway, but it might be slightly off due # to numerical inaccuracies) w = max( min(nself[3], 1.0), -1.0 ) w = acos( w ) s = sin( w ) if s < 1e-12: return (0.0, Vector(0, 0, 0)) return ( 2.0 * w, Vector(nself[0] / s, nself[1] / s, nself[2] / s) ) def as_tuple( self ): return tuple( self ) def log( self ): global zeroThreshold x, y, z, w = self b = sqrt(x**2 + y**2 + z**2) res = self.__class__() if abs( b ) <= zeroThreshold: if self.w <= zeroThreshold: raise ValueError, "math domain error" res.w = math.log( w ) else: t = atan2(b, w) f = t / b res.x = f * x res.y = f * y res.z = f * z ct = cos( t ) if abs( ct ) <= zeroThreshold: raise ValueError, "math domain error" r = w / ct if r <= zeroThreshold: raise ValueError, "math domain error" res.w = math.log( r ) return res class Matrix(list): '''deals with square matricies''' def __init__( self, values=(), size=4 ): ''' initialises a matrix from either an iterable container of values or a quaternion. in the case of a quaternion the matrix is 3x3 ''' if isinstance( values, Matrix ): size = values.size values = values.as_list() elif isinstance( values, Quaternion ): #NOTE: quaternions result in a 4x4 matrix size = 4 x, y, z, w = values xx = 2.0 * x * x yy = 2.0 * y * y zz = 2.0 * z * z xy = 2.0 * x * y zw = 2.0 * z * w xz = 2.0 * x * z yw = 2.0 * y * w yz = 2.0 * y * z xw = 2.0 * x * w row0 = 1.0-yy-zz, xy-zw, xz+yw, 0 row1 = xy+zw, 1.0-xx-zz, yz-xw, 0 row2 = xz-yw, yz+xw, 1.0-xx-yy, 0 values = row0 + row1 + row2 + (0, 0, 0, 1) if len(values) > size*size: raise MatrixException('too many args: the size of the matrix is %d and %d values were given'%(size,len(values))) self.size = size for n in range(size): row = [ 0 ] * size row[ n ] = 1 self.append( row ) for n in range( len(values) ): self[ n / size ][ n % size ] = values[ n ] def __repr__( self ): fmt = '%6.3g' asStr = [] for row in self: rowStr = [] for r in row: rowStr.append( fmt % r ) asStr.append( '[%s ]' % ','.join( rowStr ) ) return '\n'.join( asStr ) def __str__( self ): return self.__repr__() def __add__( self, other ): new = self.__class__.Zero(self.size) for i in xrange(self.size): for j in xrange(self.size): new[i][j] = self[i][j] + other[i][j] return new def __sub__( self, other ): new = self.__class__.Zero(self.size) new = self + (other*-1) return new def __mul__( self, other ): new = None if isinstance( other, (float, int) ): new = self.__class__.Zero(self.size) for i in xrange(self.size): for j in xrange(self.size): new[i][j] = self[i][j] * other elif isinstance( other, Vector ): return multMatrixVector( self, other ) else: #otherwise assume is a Matrix instance new = self.__class__.Zero( self.size ) cur = self if self.size != other.size: #if sizes are differnet - shoehorn the smaller matrix into a bigger matrix if self.size < other.size: cur = self.__class__( self, other.size ) else: other = self.__class__( other, self.size ) for i in range( self.size ): for j in range( self.size ): new[i][j] = Vector( cur[i] ) * Vector( other.getCol(j) ) return new def __div__( self, other ): return self.__mul__(1.0/other) def __eq__( self, other ): return self.isEqual(other) def __ne__( self, other ): return not self.isEqual(other) def isEqual( self, other, tolerance=1e-5 ): if self.size != other.size: return False for i in xrange(self.size): for j in xrange(self.size): if abs( self[i][j] - other[i][j] ) > tolerance: return False return True def copy( self ): return self.__class__(self,self.size) def crop( self, newSize ): new = self.__class__( size=newSize ) for n in range( newSize ): new.setRow( n, self[ n ][ :newSize ] ) return new def expand( self, newSize ): new = self.Identity( newSize ) for i in range( self.size ): for j in range( self.size ): new[ i ][ j ] = self[ i ][ j ] return new #some alternative ways to build matrix instances @classmethod def Zero( cls, size=4 ): new = cls([0]*size*size,size) return new @classmethod def Identity( cls, size=4 ): rows = [0]*size*size for n in xrange(size): rows[n+(n*size)] = 1 return cls(rows,size) @classmethod def Random( cls, size=4, range=(0,1) ): rows = [] import random for n in xrange(size*size): rows.append(random.uniform(*range)) return cls(rows,size) @classmethod def RotateFromTo( cls, fromVec, toVec, normalize=False ): '''Returns a rotation matrix that rotates one vector into another The generated rotation matrix will rotate the vector from into the vector to. from and to must be unit vectors''' e = fromVec*toVec f = e.magnitude() if f > 1.0-zeroThreshold: #from and to vector almost parallel fx = abs(fromVec.x) fy = abs(fromVec.y) fz = abs(fromVec.z) if fx < fy: if fx < fz: x = Vector(1.0, 0.0, 0.0) else: x = Vector(0.0, 0.0, 1.0) else: if fy < fz: x = Vector(0.0, 1.0, 0.0) else: x = Vector(0.0, 0.0, 1.0) u = x-fromVec v = x-toVec c1 = 2.0/(u*u) c2 = 2.0/(v*v) c3 = c1*c2*u*v res = cls(size=3) for i in xrange(3): for j in xrange(3): res[i][j] = - c1*u[i]*u[j] - c2*v[i]*v[j] + c3*v[i]*u[j] res[i][i] += 1.0 return res else: #the most common case unless from == to, or from == -to v = fromVec^toVec h = 1.0/(1.0 + e) hvx = h*v.x hvz = h*v.z hvxy = hvx*v.y hvxz = hvx*v.z hvyz = hvz*v.y row0 = e + hvx*v.x, hvxy - v.z, hvxz + v.y row1 = hvxy + v.z, e + h*v.y*v.y,hvyz - v.x row2 = hvxz - v.y, hvyz + v.x, e + hvz*v.z return cls( row0+row1+row2 ) @classmethod def FromEulerXYZ( cls, x, y, z, degrees=False ): if degrees: x,y,z = map(math.radians,(x,y,z)) cx = cos(x) sx = sin(x) cy = cos(y) sy = sin(y) cz = cos(z) sz = sin(z) row0 = cy*cz, cy*sz, -sy row1 = sx*sy*cz - cx*sz, sx*sy*sz + cx*cz, sx*cy row2 = cx*sy*cz + sx*sz, cx*sy*sz - sx*cz, cx*cy return cls( row0+row1+row2, 3 ) @classmethod def FromEulerXZY( cls, x, y, z, degrees=False ): if degrees: x,y,z = map(math.radians,(x,y,z)) cx = cos(x) sx = sin(x) cy = cos(y) sy = sin(y) cz = cos(z) sz = sin(z) row0 = cy*cz, sz, -cz*sy row1 = sx*sy - cx*cy*sz, cz*cx, cx*sy*sz + cy*sx row2 = cy*sx*sz + cx*sy, -cz*sx, cx*cy - sx*sy*sz return cls( row0+row1+row2, 3 ) @classmethod def FromEulerYXZ( cls, x, y, z, degrees=False ): if degrees: x,y,z = map(math.radians,(x,y,z)) cx = cos(x) sx = sin(x) cy = cos(y) sy = sin(y) cz = cos(z) sz = sin(z) row0 = cy*cz - sx*sy*sz, cy*sz + cz*sx*sy, -cx*sy row1 = -cx*sz, cx*cz, sx row2 = cy*sx*sz + cz*sy, sy*sz - cy*cz*sx, cx*cy return cls( row0+row1+row2, 3 ) @classmethod def FromEulerYZX( cls, x, y, z, degrees=False ): if degrees: x,y,z = map(math.radians,(x,y,z)) cx = cos(x) sx = sin(x) cy = cos(y) sy = sin(y) cz = cos(z) sz = sin(z) row0 = cy*cz, cx*cy*sz + sx*sy, cy*sx*sz - cx*sy row1 = -sz, cx*cz, cz*sx row2 = cz*sy, cx*sy*sz - cy*sx, sx*sy*sz + cx*cy return cls( row0+row1+row2, 3 ) @classmethod def FromEulerZXY( cls, x, y, z, degrees=False ): if degrees: x,y,z = map(math.radians,(x,y,z)) cx = cos(x) sx = sin(x) cy = cos(y) sy = sin(y) cz = cos(z) sz = sin(z) row0 = sx*sy*sz + cy*cz, cx*sz, cy*sx*sz - cz*sy row1 = cz*sx*sy - cy*sz, cx*cz, sy*sz + cy*cz*sx row2 = cx*sy, -sx, cx*cy return cls( row0+row1+row2, 3 ) @classmethod def FromEulerZYX( cls, x, y, z, degrees=False ): if degrees: x,y,z = map(math.radians,(x,y,z)) cx = cos(x) sx = sin(x) cy = cos(y) sy = sin(y) cz = cos(z) sz = sin(z) row0 = cy*cz, cx*sz + cz*sx*sy, sx*sz - cx*cz*sy row1 = -cy*sz, cx*cz - sx*sy*sz, cx*sy*sz + cz*sx row2 = sy, -cy*sx, cx*cy return cls( row0+row1+row2, 3 ) @classmethod def FromVectors( cls, *vectors ): values = [] for v in vectors: values.extend( list( v ) ) return cls( values, len( vectors ) ) def getRow( self, row ): return self[row] def setRow( self, row, newRow ): if len(newRow) > self.size: newRow = newRow[:self.size] if len(newRow) < self.size: newRow.extend( [0] * (self.size-len(newRow)) ) self[ row ] = newRow return newRow def getCol( self, col ): column = [0]*self.size for n in xrange(self.size): column[n] = self[n][col] return column def setCol( self, col, newCol ): newColActual = [] for row, newVal in zip( self, newCol ): row[ col ] = newVal def getDiag( self ): diag = [] for i in xrange(self.size): diag.append( self[i][i] ) return diag def setDiag( self, diag ): for i in xrange(self.size): self[i][i] = diag[i] return diag def swapRow( self, nRowA, nRowB ): rowA = self.getRow(nRowA) rowB = self.getRow(nRowB) tmp = rowA self.setRow(nRowA,rowB) self.setRow(nRowB,tmp) def swapCol( self, nColA, nColB ): colA = self.getCol(nColA) colB = self.getCol(nColB) tmp = colA self.setCol(nColA,colB) self.setCol(nColB,tmp) def transpose( self ): new = self.__class__.Zero(self.size) for i in xrange(self.size): for j in xrange(self.size): new[i][j] = self[j][i] return new def transpose3by3( self ): new = self.copy() for i in xrange(3): for j in xrange(3): new[i][j] = self[j][i] return new def det( self ): ''' calculates the determinant ''' d = 0 if self.size <= 0: return 1 if self.size == 2: #ad - bc a, b, c, d = self.as_list() return (a*d) - (b*c) for i in range( self.size ): sign = (1,-1)[ i % 2 ] cofactor = self.cofactor( i, 0 ) d += sign * self[i][0] * cofactor.det() return d determinant = det def cofactor( self, aI, aJ ): cf = self.__class__( size=self.size-1 ) cfi = 0 for i in range( self.size ): if i == aI: continue cfj = 0 for j in range( self.size ): if j == aJ: continue cf[cfi][cfj] = self[i][j] cfj += 1 cfi += 1 return cf minor = cofactor def isSingular( self ): det = self.det() if abs(det) < 1e-6: return True,0 return False,det def isRotation( self ): '''rotation matricies have a determinant of 1''' return ( abs(self.det()) - 1 < 1e-6 ) def inverse( self ): '''Each element of the inverse is the determinant of its minor divided by the determinant of the whole''' isSingular,det = self.isSingular() if isSingular: return self.copy() new = self.__class__.Zero(self.size) for i in xrange(self.size): for j in xrange(self.size): sign = (1,-1)[ (i+j) % 2 ] new[i][j] = sign * self.cofactor(i,j).det() new /= det return new.transpose() def decompose( self ): ''' return the scale matrix and rotation parts of this matrix NOTE: both are returned as 3x3 matrices ''' sx = Vector( self[ 0 ][ :3 ] ).length() sy = Vector( self[ 1 ][ :3 ] ).length() sz = Vector( self[ 2 ][ :3 ] ).length() S = type( self )( [sx,0,0, 0,sy,0, 0,0,sz], 3 ) #deal with the 3x3 until as finding the inverse of a 4x4 is considerably slower than a 3x3 S = self.getScaleMatrix() R = self.crop( 3 ) R = S.inverse() * R return R, S def getScaleMatrix( self ): ''' return the scale matrix part of this matrix ''' sx = Vector( self[ 0 ][ :3 ] ).length() sy = Vector( self[ 1 ][ :3 ] ).length() sz = Vector( self[ 2 ][ :3 ] ).length() S = type( self )( [sx,0,0, 0,sy,0, 0,0,sz], 3 ) return S def getRotationMatrix( self ): ''' returns just the rotation part of this matrix - ie scale is factored out ''' R, S = self.decompose() return R def adjoint( self ): new = self.__class__.Zero(self.size) for i in xrange(self.size): for j in xrange(self.size): new[i][j] = (1,-1)[(i+j)%2] * self.cofactor(i,j).det() return new.transpose() def ortho( self ): '''return a matrix with orthogonal base vectors''' x = Vector(self[0][:3]) y = Vector(self[1][:3]) z = Vector(self[2][:3]) xl = x.magnitude() xl *= xl y = y - ((x*y)/xl)*x z = z - ((x*z)/xl)*x yl = y.magnitude() yl *= yl z = z - ((y*z)/yl)*y row0 = ( x.x, y.x, z.x ) row1 = ( x.y, y.y, z.y ) row2 = ( x.z, y.z, z.z ) return self.__class__(row0+row1+row2,size=3) def getEigenValues( self ): m = self a, b, c = m[0] d, e, f = m[1] g, h, i = m[2] flA = -1 flB = a + e + i flC = ( d * b + g * c + f * h - a * e - a * i - e * i ) flD = ( a * e * i - a * f * h - d * b * i + d * c * h + g * b * f - g * c * e ) return cardanoCubicRoots( flA, flB, flC, flD ) def get_position( self ): return Vector( self[3][:3] ) def set_position( self, pos ): pos = Vector( pos ) self[3][:3] = pos #the following methods return euler angles of a rotation matrix def ToEulerXYZ( self, degrees=False ): easy = self[0][2] if easy == 1: z = math.pi y = -math.pi / 2.0 x = -z + atan2( -self[1][0], -self[2][0] ) elif easy == -1: z = math.pi y = math.pi / 2.0 x = z + atan2( self[1][0], self[2][0] ) else: y = -asin( easy ) cosY = cos( y ) x = atan2( self[1][2] * cosY, self[2][2] * cosY ) z = atan2( self[0][1] * cosY, self[0][0] * cosY ) angles = x, y, z if degrees: return map( math.degrees, angles ) return angles def ToEulerXZY( self, degrees=False ): easy = self[0][1] z = asin( easy ) cosZ = cos( z ) x = atan2( -self[2][1] * cosZ, self[1][1] * cosZ ) y = atan2( -self[0][2] * cosZ, self[0][0] * cosZ ) angles = x, y, z if degrees: return map( math.degrees, angles ) return angles def ToEulerYXZ( self, degrees=False ): easy = self[1][2] x = asin( easy ) cosX = cos( x ) y = atan2( -self[0][2] * cosX, self[2][2] * cosX ) z = atan2( -self[1][0] * cosX, self[1][1] * cosX ) angles = x, y, z if degrees: return map( math.degrees, angles ) return angles def ToEulerYZX( self, degrees=False ): easy = self[1][0] z = -asin( easy ) cosZ = cos( z ) x = atan2( self[1][2] * cosZ, self[1][1] * cosZ ) y = atan2( self[2][0] * cosZ, self[0][0] * cosZ ) angles = x, y, z if degrees: return map( math.degrees, angles ) return angles def ToEulerZXY( self, degrees=False ): easy = self[2][1] x = -asin( easy ) cosX = cos( x ) z = atan2( self[0][1] * cosX, self[1][1] * cosX ) y = atan2( self[2][0] * cosX, self[2][2] * cosX ) angles = x, y, z if degrees: return map( math.degrees, angles ) return angles def ToEulerZYX( self, degrees=False ): easy = self[2][0] y = asin( easy ) cosY = cos( y ) x = atan2( -self[2][1] * cosY, self[2][2] * cosY ) z = atan2( -self[1][0] * cosY, self[0][0] * cosY ) angles = x, y, z if degrees: return map( math.degrees, angles ) return angles #some conversion routines def as_list( self ): list = [] for i in xrange(self.size): list.extend(self[i]) return list def as_tuple( self ): return tuple( self.as_list() ) def cullSmallValues( self, epsilon=1e-8 ): ''' culls small values in the matrix ''' for row in self: for idx, value in enumerate( row ): if abs( value ) < epsilon: row[ idx ] = 0 ''' #the individual rotation matrices where cx = cos( x ), sx = sin( x ) etc... RX = Matrix( (1,0,0, 0,cx,sx, 0,-sx,cx) ) RY = Matrix( (cy,0,-sy, 0,1,0, sy,0,cy) ) RY = Matrix( (cz,sz,0, -sz,cz,0, 0,0,1) ) ''' def multMatrixVector( theMatrix, theVector ): ''' multiplies a matrix by a vector - returns a Vector ''' size = theMatrix.size #square matrices size = min( size, len( theVector ) ) new = theVector.Zero( size ) #init using the actual vector instance just in case its a subclass for i in range( size ): for j in range( size ): new[i] += theMatrix[i][j] * theVector[j] return new def multVectorMatrix( theVector, theMatrix ): ''' mulitplies a vector by a matrix ''' size = theMatrix.size #square matrices size = min( size, len( theVector ) ) new = theVector.Zero( size ) #init using the actual vector instance just in case its a subclass for i in range( size ): for j in range( size ): new[i] += theVector[j] * theMatrix[j][i] return new def cardanoCubicRoots( flA, flB, flC, flD ): ''' Finds the roots of a Cubic polynomial of the for ax^3 + bx^2 + cx + d = 0 Returns: True - 3 real roots exists, r0, r1, r2 False - 1 real root exists, r0, 2 complex roots exist r2, r2 ''' flSqrtThree = 1.7320508075688772 #sqrt( 3.0 ) flF = ( 3.0 * flC / flA - (flB**2) / flA**2 ) / 3.0 flG = ( 2.0 * (flB**3) / (flA**3) - 9.0 * flB * flC / (flA**2) + 27.0 * flD / flA) / 27.0 flH = flG**2 / 4.0 + flF**3 / 27.0 eigenValues = Vector.Zero( 3 ) if flF == 0 and flG == 0 and flH == 0: #3 equal roots eigenValues[0] = -( ( flD / flA )**(1/3.0) ) #cube root eigenValues[1] = flRoot0 eigenValues[2] = flRoot1 return True, eigenValues elif flH <= 0: #3 real roots flI = ( flG**2 / 4.0 - flH )**0.5 flJ = flI**(1/3.0) flK = acos( -( flG / ( 2.0 * flI ) ) ) flM = cos( flK / 3 ) flN = flSqrtThree * sin( flK / 3.0 ) flP = -( flB / ( 3.0 * flA ) ) eigenValues[0] = 2 * flJ * flM + flP eigenValues[1] = -flJ * ( flM + flN ) + flP eigenValues[2] = -flJ * ( flM - flN ) + flP return True, eigenValues #1 Real, 2 Complex Roots flR = -( flG / 2 ) + flH**0.5 flS = flR**(1/3.0) flT = -( flG / 2.0 ) - flH**0.5 flU = flT**(1/3.0) flP = -( flB / ( 3.0 * flA ) ) eigenValues[0] = ( flS + flU ) + flP #Return the real part but if it gets here there are complex roots eigenValues[1] = -( flS + flU ) / 2.0 + flP eigenValues[2] = -( flS + flU ) / 2.0 + flP return False, eigenValues #end
Python
from maya.cmds import * import re import time import api import maya.cmds as cmd mel = api.mel melecho = api.melecho def resolveCmdStr( cmdStr, obj, connects, optionals=[] ): ''' NOTE: both triggered and xferAnim use this function to resolve command strings as well ''' INVALID = '<invalid connect>' cmdStr = str( cmdStr ) #resolve # tokens - these represent self cmdStr = cmdStr.replace( '#', str( obj ) ) #resolve ranged connect array tokens: @<start>,<end> - these represent what is essentially a list slice - although they're end value inclusive unlike python slices... compile = re.compile arrayRE = compile( '(@)([0-9]+),(-*[0-9]+)' ) def arraySubRep( matchobj ): char,start,end = matchobj.groups() start = int( start ) end = int( end ) + 1 if end == 0: end = None try: return '{ "%s" }' % '","'.join( connects[ start:end ] ) except IndexError: return "<invalid range: %s,%s>" % (start, end) cmdStr = arrayRE.sub( arraySubRep, cmdStr ) #resolve all connect array tokens: @ - these are represent a mel array for the entire connects array excluding self allConnectsArray = '{ "%s" }' % '","'.join( [con for con in connects[1:] if con != INVALID] ) cmdStr = cmdStr.replace( '@', allConnectsArray ) #resolve all single connect tokens: %<x> - these represent single connects connectRE = compile('(%)(-*[0-9]+)') def connectRep( matchobj ): char, idx = matchobj.groups() try: return connects[ int(idx) ] except IndexError: return INVALID cmdStr = connectRE.sub( connectRep, cmdStr ) #finally resolve any optional arg list tokens: %opt<x>% optionalRE = compile( '(\%opt)(-*[0-9]+)(\%)' ) def optionalRep( matchobj ): charA, idx, charB = matchobj.groups() try: return optionals[ int(idx) ] except IndexError: return '<invalid optional>' cmdStr = optionalRE.sub( optionalRep, cmdStr ) return cmdStr class Trigger(object): ''' provides an interface to a trigger item ''' INVALID = '<invalid connect>' DEFAULT_MENU_NAME = '<empty>' DEFAULT_CMD_STR = '//blank' PRESET_SELECT_CONNECTED = "select -d #;\nselect -add @;" PRESET_KEY_CONNECTED = "select -d #;\nsetKeyframe @;" PRESET_TOGGLE_CONNECTED = "string $sel[] = `ls -sl`;\nint $vis = !`getAttr %1.v`;\nfor($obj in @) setAttr ($obj +\".v\") $vis;\nif( `size $sel` ) select $sel;" PRESET_TOOL_TO_MOVE = "setToolTo $gMove;" PRESET_TOOL_TO_ROTATE = "setToolTo $gRotate;" def __init__( self, obj ): if isinstance( obj, Trigger ): obj = obj.obj self.obj = obj @classmethod def CreateTrigger( cls, object, cmdStr=DEFAULT_CMD_STR, connects=None ): ''' creates a trigger and returns a new trigger instance ''' new = cls(object) new.setCmd(cmdStr) if connects: for c in connects: new.connect( str( c ) ) return new @classmethod def CreateMenu( cls, object, name=DEFAULT_MENU_NAME, cmdStr=DEFAULT_CMD_STR, slot=None ): ''' creates a new menu (optionally forces it to a given slot) and returns a new trigger instance ''' new = cls(object) new.setMenuInfo(slot, name, cmdStr) return new def __str__( self ): return str( self.obj ) def __unicode__( self ): return unicode( self.obj ) def __repr__( self ): return repr( self.__unicode__() ) def __getitem__( self, slot ): ''' returns the connect at index <slot> ''' if slot == 0: return self.obj slotPrefix = 'zooTrig' attrPath = "%s.zooTrig%d" % ( self.obj, slot ) try: objPath = cmd.connectionInfo( attrPath, sfd=True ) if objPath: return objPath.split('.')[0] except TypeError: #in this case there is no attribute - so pass and look to the connect cache pass attrPathCached = "%scache" % attrPath try: obj = cmd.getAttr( attrPathCached ) if cmd.objExists(obj): return obj except TypeError: pass raise IndexError('no such connect exists') def __len__( self ): ''' returns the number of connects ''' return len(self.connects()) def iterConnects( self ): ''' iterator that returns connectObj, connectIdx ''' return iter( self.connects()[1:] ) def iterMenus( self, resolve=False ): ''' iterator that returns slot, name, cmd ''' return iter( self.menus(resolve) ) def getCmd( self, resolve=False, optionals=[] ): attrPath = '%s.zooTrigCmd0' % self.obj if objExists( attrPath ): cmdStr = cmd.getAttr(attrPath) if resolve: return self.resolve(cmdStr,optionals) return cmdStr return None def setCmd( self, cmdStr ): cmdAttr = "zooTrigCmd0" if not objExists( "%s.%s" % ( self.obj, cmdAttr ) ): cmd.addAttr(self.obj, ln=cmdAttr, dt="string") if cmdStr is None or cmdStr == '': cmd.deleteAttr(self.obj, at=cmdAttr) return cmd.setAttr('%s.%s' % ( self.obj, cmdAttr ), cmdStr, type='string') def getMenuCmd( self, slot, resolve=False ): cmdInfo = cmd.getAttr( "%s.zooCmd%d" % ( self.obj, slot ) ) idx = cmdInfo.find('^') if resolve: return self.resolve(cmdInfo[idx+1:]) return cmdInfo[idx+1:] def setMenuCmd( self, slot, cmdStr ): newCmdInfo = '%s^%s' % ( self.getMenuName(slot), cmdStr ) cmd.setAttr("%s.zooCmd%d" % ( self.obj, slot ), newCmdInfo, type='string') def setMenuInfo( self, slot=None, name=DEFAULT_MENU_NAME, cmdStr=DEFAULT_CMD_STR ): ''' sets both the name and the command of a given menu item. if slot is None, then a new slot will be created and its values set accordingly ''' if slot is None: slot = self.nextMenuSlot() if name == '': name = self.DEFAULT_MENU_NAME #try to add the attr - if this complains then we already have the attribute... try: cmd.addAttr(self.obj, ln='zooCmd%d' % slot, dt='string') except RuntimeError: pass cmd.setAttr("%s.zooCmd%d" % ( self.obj, slot ), '%s^%s' % (name, cmdStr), type='string') self.setKillState( True ) return slot def createMenu( self, name=DEFAULT_MENU_NAME, cmdStr=DEFAULT_CMD_STR ): return self.setMenuInfo( None, name, cmdStr ) def getMenuName( self, slot ): cmdInfo = cmd.getAttr( "%s.zooCmd%d" % ( self.obj, slot ) ) idx = cmdInfo.find('^') return cmdInfo[:idx] def setMenuName( self, slot, name ): newCmdInfo = '%s^%s' % ( name, self.getMenuCmd(slot) ) cmd.setAttr("%s.zooCmd%d" % ( self.obj, slot ), newCmdInfo, type='string') def getMenuInfo( self, slot, resolve=False ): cmdInfo = cmd.getAttr( "%s.zooCmd%d" % ( self.obj, slot ) ) idx = cmdInfo.find('^') if resolve: return cmdInfo[:idx],self.resolve(cmdInfo[idx+1:]) return cmdInfo[:idx],cmdInfo[idx+1:] def menus( self, resolve=False ): ''' returns a list of tuples containing the slot,name,cmdStr for all menus on the trigger. if resolve is True, then all menu commands are returned with their symbols resolved ''' attrs = cmd.listAttr(self.obj,ud=True) slotPrefix = 'zooCmd' prefixSize = len(slotPrefix) slots = [] if attrs is None: return slots for attr in attrs: try: slot = attr[prefixSize:] except IndexError: continue if attr.startswith(slotPrefix) and slot.isdigit(): menuData = cmd.getAttr('%s.%s' % (self.obj,attr)) idx = menuData.find('^') menuName = menuData[:idx] menuCmd = menuData[idx+1:] if resolve: menuCmd = self.resolve(menuCmd) slots.append( ( int(slot), menuName, menuCmd ) ) slots.sort() return slots def connects( self ): '''returns a list of tuples with the format: (connectName,connectIdx)''' connects = [(self.obj,0)] attrs = cmd.listAttr(self.obj, ud=True) slotPrefix = 'zooTrig' prefixSize = len(slotPrefix) #the try is here simply because maya stupidly returns None if there are no attrs instead of an empty list... try: #so go through the attributes and make sure they're triggered attributes for attr in attrs: try: slot = attr[prefixSize:] except IndexError: continue if attr.startswith(slotPrefix) and slot.isdigit(): slot = int(slot) #now that we've determined its a triggered attribute, trace the connect if it exists objPath = cmd.connectionInfo( "%s.%s" % ( self.obj, attr ), sfd=True ) #append the object name to the connects list and early out if objExists(objPath): connects.append( (objPath.split('.')[0],slot) ) continue #if there is no connect, then check to see if there is a name cache, and query it - no need to #check for its existence as we're already in a try block and catching the appropriate exception #should the attribute not exist... cacheAttrName = "%s.%s%dcache" % ( self.obj, slotPrefix, slot ) cacheName = cmd.getAttr( cacheAttrName ) if objExists( cacheName ): self.connect( cacheName, slot ) #add the object to the connect slot connects.append( (cacheName, slot) ) except TypeError: pass return connects def listAllConnectSlots( self, connects=None, emptyValue=None ): ''' returns a non-sparse list of connects - unlike the connects method output, this is just a list of names. slots that have no connect attached to them have <emptyValue> as their value ''' if connects is None: connects = self.connects() #build the non-sparse connects list -first we need to find the largest connect idx, and then build a non-sparse list biggest = max( [c[1] for c in connects] ) + 1 newConnects = [emptyValue]*biggest for name, idx in connects: newConnects[idx] = str( name ) return newConnects def getConnectSlots( self, object ): '''return a list of the connect slot indicies <object> is connected to''' object = str( object ) conPrefix = 'zooTrig' prefixSize = len( conPrefix ) trigger = cmd.ls( self.obj )[0] object = cmd.ls( object )[0] slots = set() try: #if there are no connections and maya returns None connections = cmd.listConnections("%s.msg" % object, s=False, p=True) for con in connections: try: obj, attr = con.split('.') if obj != trigger: continue slot = attr[ prefixSize: ] if attr.startswith(conPrefix) and slot.isdigit(): slots.add( int(slot) ) except IndexError: pass except TypeError: pass #we need to check against all teh cache attributes to see if the object exists but has been #disconnected somehow allSlots = self.connects() getAttr = cmd.getAttr for connect, slot in allSlots: try: cacheValue = getAttr('%s.%s%dcache' % (trigger, conPrefix, slot)) if cacheValue == object: slots.add( slot ) except TypeError: pass slots = list( slots ) slots.sort() return slots def isConnected( self, object ): '''returns whether a given <object> is connected as a connect to this trigger''' object = str( object ) if not objExists(object): return [] conPrefix = 'zooTrig' cons = listConnections( '%s.message' % object, s=False, p=True ) or [] for con in cons: splits = con.split( '.' ) obj = splits[0] if obj == self.obj: if splits[1].startswith( conPrefix ): return True return False def connect( self, object, slot=None ): ''' performs the actual connection of an object to a connect slot ''' object = str( object ) if not cmd.objExists(object): return -1 #if the user is trying to connect the trigger to itself, return zero which is the reserved slot for the trigger if self.obj == object: return 0 if slot is None: slot = self.nextSlot() if slot <= 0: return 0 #make sure the connect isn't already connected - if it is, return the slot number existingSlots = self.isConnected(object) if existingSlots: return existingSlots conPrefix = 'zooTrig' prefixSize = len(conPrefix) slotPath = "%s.%s%d" % (self.obj, conPrefix, slot) if not objExists( slotPath ): cmd.addAttr(self.obj,ln= "%s%d" % (conPrefix, slot), at='message') cmd.connectAttr( "%s.msg" % object, slotPath, f=True ) self.cacheConnect( slot ) return slot def disconnect( self, objectOrSlot ): '''removes either the specified object from all slots it is connected to, or deletes the given slot index''' if isinstance(objectOrSlot,basestring): slots = self.getConnectSlots(objectOrSlot) for slot in slots: try: cmd.deleteAttr( '%s.zooTrig%d' % ( self.obj, slot )) except TypeError: pass try: cmd.deleteAttr( '%s.zooTrig%dcache' % ( self.obj, slot )) except TypeError: pass elif isinstance(objectOrSlot,(int,float)): try: cmd.deleteAttr( '%s.zooTrig%d' % ( self.obj, int(objectOrSlot) )) except TypeError: pass try: cmd.deleteAttr( '%s.zooTrig%dcache' % ( self.obj, int(objectOrSlot) )) except TypeError: pass def resolve( self, cmdStr, optionals=[] ): return resolveCmdStr( cmdStr, self.obj, self.listAllConnectSlots( emptyValue=self.INVALID ), optionals ) def unresolve( self, cmdStr, optionals=[] ): '''given a cmdStr this method will go through it looking to resolve any names into connect tokens. it only looks for single cmd tokens and optionals - it doesn't attempt to unresolve arrays''' connects = self.connects() for connect,idx in connects: connectRE = re.compile( r'([^a-zA-Z_|]+)(%s)([^a-zA-Z0-9_|]+)' % connect.replace('|','\\|') ) def tmp(match): start,middle,end = match.groups() return '%s%s%d%s' % (start,'%',idx,end) cmdStr = connectRE.sub(tmp,cmdStr) return cmdStr def replaceConnectToken( self, cmdStr, searchConnect, replaceConnect ): '''returns a resolved cmd string. the cmd string can be either passed in, or if you specify the slot number the the cmd string will be taken as the given slot's menu command''' connects = self.listAllConnectSlots() #perform some early out tests if not connects: return cmdStr if searchConnect == replaceConnect: return cmdStr #build the search and replace tokens - in the case that the replaceConnect is actually a string object, then just use it directly searchToken = '#' if searchConnect == 0 else '%'+ str(searchConnect) replaceToken = '#' if replaceConnect == 0 else '%'+ str(replaceConnect) if isinstance(replaceConnect,basestring): replaceToken = replaceConnect #build the regex to find the search data connectRE = re.compile( '(%s)([^0-9])' % searchToken ) def tokenRep( matchobj ): connectToken,trailingChar = matchobj.groups() return '%s%s' % ( replaceToken, trailingChar ) cmdStr = connectRE.sub(tokenRep,cmdStr) return cmdStr def replaceConnectInCmd( self, searchConnect, replaceConnect ): return self.replaceConnectToken( self.getCmd(slot), searchConnect, replaceConnect ) def replaceConnectInMenuCmd( self, slot, searchConnect, replaceConnect ): return self.replaceConnectToken( self.getMenuCmd(slot), searchConnect, replaceConnect ) def replaceConnectInMenuCmds( self, searchConnect, replaceConnect ): for connect,slot in self.connects: self.replaceConnectToken( self.getMenuCmd(slot), searchConnect, replaceConnect ) def scrub( self, cmdStr ): ''' will scrub any lines that contain invalid connects from the cmdStr ''' #so build the set of missing connects allSlots = self.listAllConnectSlots(emptyValue=None) numAllSlots = len(allSlots) missingSlots = set( [idx for idx,val in enumerate(allSlots) if val is None] ) #now build the list of connect tokens used in the cmd and compare it with the connects #that are valid - in the situation where there are connects in the cmdStr that don't #exist on the trigger, we want to scrub these singleRE = re.compile('%([0-9]+)') subArrayRE = re.compile('@([0-9]+),(-*[0-9]+)') nonexistantSlots = set( map(int, singleRE.findall(cmdStr)) ) for start,end in subArrayRE.findall(cmdStr): start = int(start) end = int(end) if end < 0: end += numAllSlots else: end += 1 [nonexistantSlots.add(slot) for slot in xrange( start, end )] [nonexistantSlots.discard( slot ) for slot,connect in enumerate(allSlots)] missingSlots = missingSlots.union( nonexistantSlots ) #now add the nonexistantSlots to the missingSlots #early out if we can if not missingSlots: return cmdStr #otherwise iterate over the list of slots and remove any line that has that slot token in it for slot in missingSlots: missingRE = re.compile(r'''^(.*)(%-*'''+ str(slot) +')([^0-9].*)$\n',re.MULTILINE) cmdStr = missingRE.sub('',cmdStr) def replaceSubArray( matchObj ): junk1,start,end,junk2 = matchObj.groups() start = int(start) end = int(end) if end<0: end = start+end else: end += 1 subArrayNums = set(range(start,end)) common = subArrayNums.intersection( missingSlots ) if common: return '' return matchObj.string[matchObj.start():matchObj.end()] subArrayRE = re.compile('^(.*@)([0-9]+),(-*[0-9]+)([^0-9].*)$\n',re.MULTILINE) cmdStr = subArrayRE.sub(replaceSubArray,cmdStr) return cmdStr def scrubCmd( self ): ''' convenience method for performing self.scrub on the trigger command ''' self.setCmd( self.scrub( self.getCmd() )) def scrubMenuCmd( self, slot ): ''' convenience method for performing self.scrub on a given menu command ''' self.setMenuCmd(slot, self.scrub( self.getMenuCmd(slot) )) def scrubMenuCmds( self ): ''' convenience method for performing self.scrub on all menu commands ''' for slot,name,cmdStr in self.menus(): self.scrubMenuCmd(slot) def collapseMenuCmd( self, slot ): ''' resolves a menu item's command string and writes it back to the menu item - this is most useful when connects are being re-shuffled and you don't want to have to re-write command strings. there is the counter function - uncollapseMenuCmd that undoes the results ''' self.setMenuCmd(slot, self.getMenuCmd(slot,True) ) def uncollapseMenuCmd( self, slot ): self.setMenuCmd(slot, self.unresolve( self.getMenuCmd(slot) ) ) def eval( self, cmdStr, optionals=[] ): return mel.eval( self.resolve(cmdStr,optionals) ) def evalCmd( self ): return self.eval( self.getCmd() ) def evalMenu( self, slot ): return self.eval( self.getMenuCmd(slot) ) def evalCareful( self, cmdStr, optionals=[] ): ''' does an eval on a line by line basis, catching errors as they happen - its most useful for when you have large cmdStrs with only a small number of errors ''' start = time.clock() lines = cmdStr.split('\n') evalMethod = mel.eval validLines = [] for line in lines: try: cmd.select(cl=True) #selection is cleared so any missing connects don't work on selection instead of specified objects resolvedLine = self.resolve(line,optionals) evalMethod(resolvedLine) except RuntimeError: continue validLines.append( line ) end = time.clock() print 'time taken', end-start, 'seconds' return '\n'.join(validLines) def evalForConnectsOnly( self, cmdStr, connectIdxs, optionals=[] ): ''' will do an eval only if one of the connects in the given a list of connects is contained in the command string ''' return self.eval( self.filterConnects( cmdStr, connectIdxs ), optionals ) def filterConnects( self, cmdStr, connectIdxs ): ''' will return the lines of a command string that refer to connects contained in the given list ''' connectIdxs = set(connectIdxs) allSlots = self.listAllConnectSlots(emptyValue=None) numAllSlots = len(allSlots) lines = cmdStr.split('\n') singleRE = re.compile('%([0-9]+)') subArrayRE = re.compile('@([0-9]+),(-*[0-9]+)') validLines = [] for line in lines: #are there any singles in the line? singles = set( map(int, singleRE.findall(line)) ) if connectIdxs.intersection(singles): validLines.append(line) continue #check if there are any sub arrays which span the any of the connects? subArrays = subArrayRE.findall(line) for sub in subArrays: start = int(sub[0]) end = int(sub[1]) if end < 0: end += numAllSlots else: end += 1 subRange = set( range(start,end) ) if connectIdxs.intersection(subRange): validLines.append(line) break #finally check to see if there are any single array tokens - these are always added #NOTE: this check needs to happen AFTER the subarray check - at least in its current state - simply because its such a simple (ie fast) test if line.find('@') >= 0: validLines.append(line) continue return '\n'.join(validLines) def removeCmd( self, removeConnects=False ): '''removes the triggered cmd from self - can optionally remove all the connects as well''' try: #catches the case where there is no trigger cmd... faster than a object existence test cmd.deleteAttr( '%s.zooTrigCmd0' % self.obj ) if removeConnects: for connect,slot in self.connects(): self.disconnect(slot) except TypeError: pass def removeMenu( self, slot, removeConnects=False ): ''' removes a given menu slot - if removeConnects is True, all connects will be removed ONLY if there are no other menu cmds ''' attrpath = '%s.zooCmd%d' % ( self.obj, slot ) try: cmd.deleteAttr( '%s.zooCmd%d' % ( self.obj, slot )) if removeConnects and not self.menus(): for connect,slot in self.connects(): self.disconnect(slot) except TypeError: pass def removeAll( self, removeConnects=False ): ''' removes all triggered data from self ''' self.removeCmd(removeConnects) for idx,name,cmd in self.menus(): self.removeMenu(idx) def nextSlot( self ): ''' returns the first available slot index ''' slots = self.listAllConnectSlots(emptyValue=None) unused = [con for con,obj in enumerate(slots) if obj is None] next = 1 if unused: return unused[0] elif slots: return len(slots) return next def nextMenuSlot( self ): ''' returns the first available menu slot index ''' slots = self.menus() next = 0 if slots: return slots[-1][0] + 1 return next def cacheConnect( self, slot ): '''caches the objectname of a slot connection''' try: connectName = self[ slot ] except IndexError: return None slotPrefix = 'zooTrig' cacheAttrName = '%s%dcache' % ( slotPrefix, slot ) cacheAttrPath = '%s.%s' % ( self.obj, cacheAttrName ) if not cmd.objExists( cacheAttrPath ): cmd.addAttr( self.obj, ln=cacheAttrName, dt='string' ) cmd.setAttr( cacheAttrPath, connectName, type='string' ) def validateConnects( self ): '''connects maintain a cache which "remembers" the last object that was plugged into them. this method will run over all connects and for those unconnected ones, it will look for the object that it USED to be connected to and connect it, and for those that ARE connected, it will make sure the cache is valid. the cache can become invalid if a connected object's name changes after it was connected''' slotPrefix = 'zooTrig' for connect,slot in self.iterConnects(): attrpath = '%s.%s%d' % ( self.obj, slotPrefix, slot ) objPath = cmd.connectionInfo(attrpath, sfd=True) if not cmd.objExists( objPath ): #get the cached connect and attach it cachedValue = cmd.getAttr('%scache' % attrpath) if cmd.objExists(cachedValue): self.connect(cachedValue,slot) def setKillState( self, state ): '''so the kill state tells the objMenu build script to stop after its build all menu items listed on the object - this method provides an interface to enabling/disabling that setting''' attr = 'zooObjMenuDie' attrpath = '%s.%s' % ( self.obj, attr ) if state: if not objExists( attrpath ): cmd.addAttr(self.obj, at="bool", ln=attr) cmd.setAttr(attrpath, 1) else: if objExists( attrpath ): cmd.deleteAttr(attrpath) def getKillState( self ): attrpath = "%s.zooObjMenuDie" % self.obj if objExists( attrpath ): return bool( cmd.getAttr(attrpath) ) return False killState = property(getKillState,setKillState) def getConnectIndiciesForObjects( self, objects=None ): '''returns a list of connection indicies for the given list of objects. NOTE: these list lengths may not match - it is perfectly valid for a single object to be connected to multiple connect slots''' if objects is None: objects = cmd.ls(sl=True) cons = [] for obj in objects: cons.extend( self.getConnectSlots(obj) ) return cons def addConnect( obj, connectObj, slot=None ): return Trigger( obj ).connect( connectObj, slot ) def setKillState( obj, state ): return Trigger( obj ).setKillState( state ) def getKillState( obj ): return Trigger( obj ).getKillState() def writeSetAttrCmd( trigger, objs ): cmdLines = [] trigger = Trigger(trigger) for obj in objs: attrs = cmd.listAttr(obj, k=True, s=True, v=True, m=True) objSlot = trigger.getConnectSlots(obj) slots = trigger.getConnectSlots(obj) if len(slots): objStr = "%"+ str(slots[0]) for a in attrs: attrType = cmd.getAttr( "%s.%s"%(obj,a), type=True ) if attrType.lower() == "double": attrVal = cmd.getAttr( "%s.%s" % (obj,a) ) cmdLines.append( "setAttr %s.%s %0.5f;" % ( objStr, a, attrVal ) ) else: cmdLines.append( "setAttr %s.%s %s;" % ( objStr, a, cmd.getAttr( "%s.%s"%(obj,a) ) ) ) return '\n'.join( cmdLines ) def listTriggers(): '''lists all trigger objects in the current scene''' allObjects = cmd.ls(type='transform') triggers = [] attr = 'zooTrigCmd0' try: for obj in allObjects: if objExists( '%s.%s' % ( obj, attr ) ): triggers.connect( obj ) except TypeError: pass return triggers def listObjectsWithMenus(): '''lists all objects with menu items in the scene''' allObjects = cmd.ls(type='transform') objMenus = [] attrPrefix = 'zooCmd' prefixSize = len(attrPrefix) for obj in allObjects: attrs = cmd.listAttr(obj, ud=True) try: for attr in attrs: try: slot = attr[prefixSize:] except IndexError: continue if attr.startswith(attrPrefix) and slot.isdigit(): objMenus.append( obj ) break except TypeError: continue return objMenus def getTriggeredState(): '''returns the state of triggered''' return mel.zooTriggeredState() def setTriggeredState( state=True ): if state: mel.zooTriggeredLoad() else: mel.zooTriggeredUnload() def longname( object ): try: longname = cmd.ls(object,long=True) return longname[0] except IndexError: raise TypeError #end
Python
from baseMelUI import * from filesystem import Path import maya.cmds as cmd import poseSym import os LabelledIconButton = labelledUIClassFactory( MelIconButton ) class PoseSymLayout(MelVSingleStretchLayout): ICONS = ICON_SWAP, ICON_MIRROR, ICON_MATCH = 'poseSym_swap.xpm', 'poseSym_mirror.xpm', 'poseSym_match.xpm' def __init__( self, parent ): self.UI_swap = swap = LabelledIconButton( self, llabel='swap pose', llabelWidth=65, llabelAlign='right', c=self.on_swap ) swap.setImage( self.ICON_SWAP ) self.UI_mirror = mirror = LabelledIconButton( self, llabel='mirror pose', llabelWidth=65, llabelAlign='right', c=self.on_mirror ) mirror.setImage( self.ICON_MATCH ) #self.UI_match = match = LabelledIconButton( self, llabel='match pose', llabelWidth=65, llabelAlign='right', c=self.on_match ) #match.setImage( self.ICON_MATCH ) spacer = MelSpacer( self ) hLayout = MelHLayout( self ) MelLabel( hLayout, l='mirror: ' ) self.UI_mirror_t = MelCheckBox( hLayout, l='translate', v=1 ) self.UI_mirror_r = MelCheckBox( hLayout, l='rotate', v=1 ) self.UI_mirror_other = MelCheckBox( hLayout, l='other', v=1 ) hLayout.layout() self.setStretchWidget( spacer ) self.layout() ### EVENT HANDLERS ### def on_swap( self, *a ): for pair, obj in poseSym.iterPairAndObj( cmd.ls( sl=True ) ): pair.swap( t=self.UI_mirror_t.getValue(), r=self.UI_mirror_r.getValue(), other=self.UI_mirror_other.getValue() ) def on_mirror( self, *a ): for pair, obj in poseSym.iterPairAndObj( cmd.ls( sl=True ) ): pair.mirror( obj==pair.controlA, t=self.UI_mirror_t.getValue(), r=self.UI_mirror_r.getValue(), other=self.UI_mirror_other.getValue() ) def on_match( self, *a ): for pair, obj in poseSym.iterPairAndObj( cmd.ls( sl=True ) ): pair.match( obj==pair.controlA, t=self.UI_mirror_t.getValue(), r=self.UI_mirror_r.getValue(), other=self.UI_mirror_other.getValue() ) class PoseSymWindow(BaseMelWindow): WINDOW_NAME = 'PoseSymTool' WINDOW_TITLE = 'Pose Symmetry Tool' DEFAULT_SIZE = 280, 200 DEFAULT_MENU = 'Setup' HELP_MENU = WINDOW_NAME, 'hamish@valvesoftware.com', 'https://intranet.valvesoftware.com/wiki/index.php/Pose_Mirror_Tool' FORCE_DEFAULT_SIZE = True def __init__( self ): self.editor = PoseSymLayout( self ) self.setupMenu() self.show() def setupMenu( self ): menu = self.getMenu( 'Setup' ) menu.clear() MelMenuItem( menu, l='Create Paired Mirror', ann='Will put the two selected objects into a "paired" relationship - they will know how to mirror/exchange poses with one another', c=self.on_setupPair ) MelMenuItem( menu, l='Create Single Mirror For Selected', ann='Will setup each selected control with a mirror node so it knows how to mirror poses on itself', c=self.on_setupSingle ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='Auto Setup Skeleton Builder', ann='Tries to determine mirroring relationships from skeleton builder', c=self.on_setupSingle ) ### EVENT HANDLERS ### def on_setupPair( self, *a ): sel = cmd.ls( sl=True, type='transform' ) if len( sel ) == 1: pair = poseSym.ControlPair.Create( sel[0] ) cmd.select( pair.node ) elif len( sel ) >= 2: pair = poseSym.ControlPair.Create( sel[0], sel[1] ) cmd.select( pair.node ) def on_setupSingle( self, *a ): sel = cmd.ls( sl=True, type='transform' ) nodes = [] for s in sel: pair = poseSym.ControlPair.Create( s ) nodes.append( pair.node ) cmd.select( nodes ) def on_setupSkeletonBuilder( self, *a ): import rigPrimitives rigPrimitives.setupMirroring() #end
Python
from baseMelUI import * from maya.mel import eval as evalMel from filesystem import Path from common import printErrorStr import re import maya try: #try to connect to wing - otherwise don't worry import wingdbstub except ImportError: pass def setupDagProcMenu(): ''' sets up the modifications to the dagProcMenu script ''' dagMenuScript = r'C:\Program Files\Autodesk\Maya2011\scripts\others\dagMenuProc.mel' globalProcDefRex = re.compile( "^global +proc +dagMenuProc *\( *string *(\$[a-zA-Z0-9_]+), *string *(\$[a-zA-Z0-9_]+) *\)" ) dagMenuScriptLines = Path( dagMenuScript ).read() dagMenuScriptLineIter = iter( dagMenuScriptLines ) newLines = [] hasDagMenuProcBeenSetup = False for line in dagMenuScriptLineIter: newLines.append( line ) globalProcDefSearch = globalProcDefRex.search( line ) if globalProcDefSearch: parentVarStr, objectVarStr = globalProcDefSearch.groups() selHierarchyRex = re.compile( 'uiRes *\( *"m_dagMenuProc.kSelectHierarchy" *\)' ) #menuItem -label (uiRes("m_dagMenuProc.kDagMenuSelectHierarchy")) -c ("select -hierarchy " + $object); #if we're past the global proc definition for dagMenuProc start looking for the menu item to for line in dagMenuScriptLineIter: newLines.append( line ) if 'menuItem' in line and selHierarchyRex.search( line ): newLines.append( '\t\t\tmenuItem -d 1;' ) newLines.append( '\t\t\tpython( "import triggeredUI" );' ) newLines.append( """\t\t\tint $killState = python( "triggeredUI.buildMenuItems( '"+ %s +"', '"+ %s +"' )" );""" % (parentVarStr, objectVarStr) ) newLines.append( '\t\t\tif( $killState ) return;' ) hasDagMenuProcBeenSetup = True break if not hasDagMenuProcBeenSetup: printErrorStr( "Couldn't auto setup dagMenuProc! AWOOGA!" ) return newScript = '\n'.join( newLines ) evalMel( newScript ) def setupZooToolBox(): #all the files for zooToolBox should live in the same directory as this script, including plug-ins thisFile = Path( __file__ ) thisPath = thisFile.up() existingPlugPathStr = maya.mel.eval( 'getenv MAYA_PLUG_IN_PATH;' ) existingPlugPaths = existingPlugPathStr.split( ';' ) newPlugPaths = [] pathsAlreadyInList = set() zooPlugPathAdded = False for path in existingPlugPaths: path = Path( path ) if path in pathsAlreadyInList: continue pathsAlreadyInList.add( path ) newPlugPaths.append( path.unresolved() ) if path == thisPath: zooPlugPathAdded = True if not zooPlugPathAdded: newPlugPaths.append( thisPath ) newPlugPathStr = ';'.join( newPlugPaths ) maya.mel.eval( 'putenv MAYA_PLUG_IN_PATH "%s";' % newPlugPathStr ) #now setup the dagMenuProc setupDagProcMenu() def loadZooPlugin( pluginName ): try: cmd.loadPlugin( pluginName, quiet=True ) except: setupZooToolBox() try: cmd.loadPlugin( pluginName, quiet=True ) except: maya.OpenMaya.MGlobal.displayError( 'Failed to load zooMirror.py plugin - is it in your plugin path?' ) def loadSkeletonBuilderUI( *a ): import skeletonBuilderUI skeletonBuilderUI.SkeletonBuilderWindow() def loadSkinPropagation( *a ): import refPropagation refPropagation.propagateWeightChangesToModel_confirm() def loadPicker( *a ): import picker picker.PickerWindow() class ToolCB(object): def __init__( self, melStr ): self.cmdStr = melStr def __call__( self, *a ): evalMel( self.cmdStr ) #this describes the tools to display in the UI - the nested tuples contain the name of the tool as displayed #in the UI, and a tuple containing the annotation string and the button press callback to invoke when that #tool's toolbox button is pressed. #NOTE: the press callback should take *a as its args TOOL_CATS = ( ('rigging', (('Skeleton Builder - the new CST', "Skeleton Builder is what zooCST initially set out to be", loadSkeletonBuilderUI), ('Skinning Propagation', "Propagates skinning changes made to referenced geometry to the file it lives in", loadSkinPropagation), ('zooCST', 'The ghetto version of Skeleton Builder', None), ('zooTriggered', 'zooTriggered is one of the most powerful rigging companions around. It allows the rigger to attach name independent MEL commands to an object. These commands can be run either on the selection of the object, or by right clicking over that object.\n\nIt allows context sensitive scripted commands to be added to a character rig, which allows the rigger to create more intuitive rigs. Being able to add name independent MEL scripts to a rig can open up entire new worlds of possibilities, as does selection triggered MEL commands.', None), #('zooTriggerator', '''zooTriggerator is an interface for building and managing triggered viewport interfaces. It builds collapsible, in-viewport folders that contain selection triggers.\n\nThey can be used to build selection triggers for complex rigs to make an easy to use interface for animators to use.''', None), ('zooKeymaster', 'keymaster gives you a heap of tools to manipulate keyframes - scaling around curve pivots, min/max scaling of curves/keys etc...', ToolCB( 'source zooKeymaster; zooKeymasterWin;' )), ('zooSurgeon', 'zooSurgeon will automatically cut up a skinned mesh and parent the cut up "proxy" objects to the skeleton. This allows for near instant creation of a fast geometrical representation of a character.', None), ('zooVisMan', 'visMan is a tool for creating and using heirarchical visibility sets in your scene. a visibility set holds a collection of items, be it components, objects or anything else that normally fits into a set. the sets can be organised heirarchically, and easily collapsed, and selected in a UI to show only certain objects in your viewports. its great for working with large sets, or breaking a character up into parts to focus on', None))), ('animation', (('zooPicker', 'Picker tool - provides a way to create buttons that select scene objects, or run arbitrary code', loadPicker), ('zooAnimStore', '', None), ('zooXferAnim', 'zooXferAnim is an animation transfer utility. It allows transfer of animation using a variety of different methods, instancing, duplication, copy/paste, import/export and tracing. Its also fully externally scriptable for integration into an existing production pipeline.', None), ('zooGraphFilter', 'zooGraphFilter provides a quick and easy way of filtering out certain channels on many objects in the graph editor.', None), ('zooKeyCommands', 'zooKeyCommands is a simple little tool that lets you run a MEL command on an object for each keyframe the object has. It basically lets you batch a command for each keyframe.', None), ('zooGreaseMonkey', 'zooGreaseMonkey is a neat little script that allows you to draw in your camera viewport. It lets you add as many frames as you want at various times in your scene. You can use it to thumbnail your animation in your viewport, you can use it to plot paths, you could even use it to do a simple 2d based animation if you wanted.', None), ('zooShots', 'zooShots is a camera management tool. It lets you create a bunch of cameras in your scene, and "edit" them together in time. The master camera then cuts between each "shot" camera. All camera attributes are maintained over the cut - focal length, clipping planes, fstop etc...\n\nThe interface allows you to associate notes with each shot, colour shots in the UI to help group like shots, shot numbering etc...', None), ('zooHUDCtrl', 'zooHUDCtrl lets you easily add stuff to your viewport HUD. It supports custom text, filename, current frame, camera information, object attribute values, and if you are using zooShots, it will also print out shot numbers to your HUD.', None))), ('general', (('zooAutoSave', '''zooAutoSave is a tool that will automatically save your scene after a certain number of selections. Maya doesn't provide a timer, so its not possible to write a time based autosave tool, but it makes more sense to save automatically after you've done a certain number of "things". You can easily adjust the threshold, and have the tool automatically start when maya starts if you wish.''', None), #('zooReblender', '', None), )), ('hotkeys', (('zooAlign', 'snaps two objects together - first select the master object, then the object you want to snap, then hit the hotkey', ToolCB( 'zooHotkeyer zooAlign "{zooAlign \"-load 1\";\nstring $sel[] = `ls -sl`;\nfor( $n=1; $n<`size $sel`; $n++ ) zooAlignSimple $sel[0] $sel[$n];}" "" "-default a -alt 1 -enableMods 1 -ann aligns two objects"')), ('zooSetMenu', 'zooSetMenu us a marking menu that lets you quickly interact with all quick selection sets in your scene.', ToolCB( "zooHotkeyer zooSetMenu \"zooSetMenu;\" \"zooSetMenuKillUI;\" \"-default y -enableMods 0 -ann zooSetMenu lets you quickly interact with selection sets in your scene through a marking menu interface\";" )), ('zooTangentWks', 'zooTangentWks is a marking menu script that provides super fast access to common tangent based operations. Tangent tightening, sharpening, change tangent types, changing default tangents etc...', ToolCB( "zooHotkeyer zooTangentWks \"zooTangentWks;\" \"zooTangentWksKillUI;\" \"-default q -enableMods 0 -ann tangent works is a marking menu script to speed up working with the graph editor\";" )), ('zooSetkey', 'zooSetKey is a tool designed to replace the set key hotkey. It is a marking menu script that lets you perform a variety of set key based operations - such as push the current key to the next key, perform a euler filter on all selected objects etc...', ToolCB( "zooHotkeyer zooSetkey \"zooSetkey;\" \"zooSetkeyKillUI;\" \"-default s -enableMods 0 -ann designed to replace the set key hotkey, this marking menu script lets you quickly perform all kinda of set key operations\";" )), ('zooCam', 'zooCam is a marking menu that lets you quickly swap between any camera in your scene. It is integrated tightly with zooShots, so you can quickly navigate between shot cameras, master cameras, or any other in-scene camera.', ToolCB( "zooHotkeyer zooCam \"zooCam;\" \"zooCamKillUI;\" \"-default l -enableMods 0 -ann zooCam marking menu script for managing in scene cameras\";" )), ('toggle_shading', 'toggles viewport shading', ToolCB( "zooHotkeyer toggleShading \"zooToggle shading;\" \"\" \"-default 1 -enableMods 1 -ann toggles viewport shading\"" )), ('toggle_texturing', 'toggles viewport texturing', ToolCB( "zooHotkeyer toggleTexture \"zooToggle texturing;\" \"\" \"-default 2 -enableMods 1 -ann toggles viewport texturing\"" )), ('toggle_lights', 'toggles viewport lighting', ToolCB( "zooHotkeyer toggleLights \"zooToggle lighting;\" \"\" \"-default 3 -enableMods 1 -ann toggles viewport lighting\"" )))) ) class ToolboxTab(MelColumnLayout): def __new__( cls, parent, toolTuples ): return MelColumnLayout.__new__( cls, parent ) def __init__( self, parent, toolTuples ): MelColumnLayout.__init__( self, parent ) for toolStr, annStr, pressCB in toolTuples: if pressCB is None: pressCB = ToolCB( '%s;' % toolStr ) MelButton( self, l=toolStr, ann=annStr, c=pressCB ) class ToolboxTabs(MelTabLayout): def __init__( self, parent ): n = 0 for toolCatStr, toolTuples in TOOL_CATS: ui = ToolboxTab( self, toolTuples ) self.setLabel( n, toolCatStr ) n += 1 class ToolboxWindow(BaseMelWindow): WINDOW_NAME = 'zooToolBox' WINDOW_TITLE = 'zooToolBox ::macaroniKazoo::' DEFAULT_SIZE = 400, 300 FORCE_DEFAULT_SIZE = True DEFAULT_MENU = None def __init__( self ): setupZooToolBox() ToolboxTabs( self ) self.show() #end
Python
import maya.cmds as cmd class KeyServer(object): ''' This class is basically an iterator over keys set on the given objects. Key times are iterated over in chronological order. Calling getNodes on the iterator will provide a list of nodes that have keys on the current frame ''' def __init__( self, nodes, changeTime=True ): self._nodes = nodes self._changeTime = changeTime self._curIndex = 0 self._keys = list( set( cmd.keyframe( nodes, q=True ) or [] ) ) self._keys.sort() self._keyNodeDict = {} self._keyNodeDictHasBeenPopulated = False def _populateDict( self ): keyNodeDict = self._keyNodeDict for node in self._nodes: keys = cmd.keyframe( node, q=True ) if keys: for key in set( keys ): keyNodeDict.setdefault( key, [] ) keyNodeDict[ key ].append( node ) self._keyNodeDictHasBeenPopulated = True def getNodesAtTime( self ): if not self._keyNodeDictHasBeenPopulated: self._populateDict() keyNodeDict = self._keyNodeDict return keyNodeDict[ self._keys[ self._curIndex ] ][:] def __iter__( self ): for key in self._keys: if self._changeTime: cmds.currentTime( key, e=True ) yield key #end
Python
from data import * def themeTest(): print "I am the default theme!" def setFont(obj): obj.setFont("Devinne Swash", 16) def addPythonButton(gump, coordinates, callback): b = gump.addPythonButton(coordinates, Texture(TextureSource.THEME, "images/button.png"), callback) styleButton(b) return b def addPageButton(gump, coordinates, page): b = gump.addPageButton(coordinates, Texture(TextureSource.THEME, "images/button.png"), page) styleButton(b) return b def addServerButton(gump, coordinates, buttonId): b = gump.addPageButton(coordinates, Texture(TextureSource.THEME, "images/button.png"), buttonId) styleButton(b) return b def styleButton(b): b.state("mouseOver").rgba = rgba("#cceecc") b.state("mouseDown").rgba = rgba("#ccffcc") b.setFont("Devinne Swash", 18) def addScrollArea(gump, coordinates): scroll = gump.addScrollArea(coordinates) scroll.vertical.width = 15 scroll.vertical.increment.texture = Texture(TextureSource.THEME, "images/scroll_increment.png") scroll.vertical.incrementMouseOver.rgba = rgba("#cceecc") scroll.vertical.incrementMouseDown.rgba = rgba("#ccffcc") scroll.vertical.decrement.texture = Texture(TextureSource.THEME, "images/scroll_decrement.png") scroll.vertical.decrementMouseOver.rgba = rgba("#cceecc") scroll.vertical.decrementMouseDown.rgba = rgba("#ccffcc") scroll.vertical.thumb.texture = Texture(TextureSource.THEME, "images/scroll_thumb.png") scroll.vertical.thumbMouseOver.rgba = rgba("#cceecc") scroll.vertical.thumbMouseDown.rgba = rgba("#ccffcc") scroll.vertical.track.texture = Texture(TextureSource.THEME, "images/scroll_track.png") return scroll def addCheckbox(gump, coordinates): cb = gump.addCheckbox(coordinates) cb.state("checked").texture = Texture(TextureSource.THEME, "images/checkbox_checked.png") cb.state("checkedMouseOver").texture = Texture(TextureSource.THEME, "images/checkbox_checked.png") cb.state("checkedMouseOver").rgba = rgba("#cceecc") cb.state("unchecked").texture = Texture(TextureSource.THEME, "images/checkbox.png") cb.state("uncheckedMouseOver").texture = Texture(TextureSource.THEME, "images/checkbox.png") cb.state("uncheckedMouseOver").rgba = rgba("#cceecc") return cb
Python
from data import * def themeTest(): print "I am the preshard theme!" def setFont(obj): obj.setFont("Devinne Swash", 16) def addPythonButton(gump, coordinates, callback): b = gump.addPythonButton(coordinates, Texture(TextureSource.THEME, "images/button.png"), callback) styleButton(b) return b def addPageButton(gump, coordinates, page): b = gump.addPageButton(coordinates, Texture(TextureSource.THEME, "images/button.png"), page) styleButton(b) return b def addServerButton(gump, coordinates, buttonId): b = gump.addPageButton(coordinates, Texture(TextureSource.THEME, "images/button.png"), buttonId) styleButton(b) return b def styleButton(b): b.state("mouseOver").rgba = rgba("#cceecc") b.state("mouseDown").rgba = rgba("#ccffcc") b.setFont("Devinne Swash", 18) def addScrollArea(gump, coordinates): scroll = gump.addScrollArea(coordinates) scroll.vertical.width = 15 scroll.vertical.increment.texture = Texture(TextureSource.THEME, "images/scroll_increment.png") scroll.vertical.incrementMouseOver.rgba = rgba("#cceecc") scroll.vertical.incrementMouseDown.rgba = rgba("#ccffcc") scroll.vertical.decrement.texture = Texture(TextureSource.THEME, "images/scroll_decrement.png") scroll.vertical.decrementMouseOver.rgba = rgba("#cceecc") scroll.vertical.decrementMouseDown.rgba = rgba("#ccffcc") scroll.vertical.thumb.texture = Texture(TextureSource.THEME, "images/scroll_thumb.png") scroll.vertical.thumbMouseOver.rgba = rgba("#cceecc") scroll.vertical.thumbMouseDown.rgba = rgba("#ccffcc") scroll.vertical.track.texture = Texture(TextureSource.THEME, "images/scroll_track.png") return scroll def addCheckbox(gump, coordinates): cb = gump.addCheckbox(coordinates) cb.state("checked").texture = Texture(TextureSource.THEME, "images/checkbox_checked.png") cb.state("checkedMouseOver").texture = Texture(TextureSource.THEME, "images/checkbox_checked.png") cb.state("checkedMouseOver").rgba = rgba("#cceecc") cb.state("unchecked").texture = Texture(TextureSource.THEME, "images/checkbox.png") cb.state("uncheckedMouseOver").texture = Texture(TextureSource.THEME, "images/checkbox.png") cb.state("uncheckedMouseOver").rgba = rgba("#cceecc") return cb
Python
from data import * from ui import * import client import theme # In case you want to redesign this gump, keep in mind that at this point, you can not # access any uo data (e.g. art.mul graphics, hues), as the mul files are not loaded yet. def create(args): g = GumpMenu("shardlist", 400, 300) g.closable = False shardlist = args["shardlist"] if len(shardlist) > 0: g.onEnter = selectFirst g.store["firstName"] = shardlist[0] else: g.onEnter = createShard g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_250x250.png")) scroll = theme.addScrollArea(g, (20, 20, 210, 137)) y = 0 for shard in shardlist: btnShard = theme.addPythonButton(scroll, (0, y, 190, 25), selectShard) btnShard.text = shard btnShard.store["shard"] = shard y += 28 scroll.updateScrollbars() btnCreate = theme.addPythonButton(g, (20, 175, 210, 25), createShard) btnCreate.text = "Create shard" btnExit = theme.addPythonButton(g, (20, 203, 210, 25), shutdown) btnExit.text = "Exit" def createShard(button): client.openGump("createshard") # don't close the gump, shard creation can be cancelled return False def shutdown(button): client.shutdown() return True def selectFirst(gump): client.setShard(gump.store["firstName"]) return True def selectShard(button): client.setShard(button.store["shard"]) return True
Python
from data import * from ui import * import client import theme def create(args): g = GumpMenu("serverlist", 400, 300) g.closable = False print args serverList = args["serverlist"] # serverlist is a list of tuples (index, name) if len(serverList) > 0: g.onEnter = selectFirst g.store["firstServer"] = serverList[0][0] g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_250x250.png")) scroll = theme.addScrollArea(g, (20, 20, 210, 137)) y = 0 for (idx, name) in serverList: btnServer = theme.addPythonButton(scroll, (0, y, 190, 25), selectServer) btnServer.text = name btnServer.store["server"] = idx y += 28 scroll.updateScrollbars() btnDisconnect = theme.addPythonButton(g, (20, 175, 210, 25), disconnect) btnDisconnect.text = "Disconnect" btnExit = theme.addPythonButton(g, (20, 203, 210, 25), shutdown) btnExit.text = "Exit" def disconnect(button): client.disconnect() button.gump.close() return True def shutdown(button): client.shutdown() return True def selectFirst(gump): client.selectServer(gump.store["firstServer"]) gump.close() return True def selectServer(button): client.selectServer(button.store["server"]) button.gump.close() return True
Python
from ui import * from data import * import world def create(args): g = GumpMenu("profile", args.get("x", 100), args.get("y", 100)) g.mobile = args["mobile"] # TODO: make this look like the uo one g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_250x250.png")) # TODO: editable for own profile g.addPropertyLabel((10, 10, 230, 40), "profile-header") g.addPropertyLabel((10, 55, 230, 140), "profile-text") g.addPropertyLabel((10, 205, 230, 40), "profile-static") def save(gump): saveData = { "x": gump.x, "y": gump.y, # To be able to also restore the gump after a restart, save only the serial "serial": gump.mobile.serial } return saveData def load(saveData): mob = world.getMobile(saveData["serial"]) if mob: saveData["mobile"] = mob gump = create(saveData) # request profile data from server saveData["mobile"].openProfile()
Python
from ui import * from data import * def init(gump): gump.setFont("unifont1", 12, False) def addHtmlBackground(gump, geom): return gump.addBackground(geom, 3000) def addHtmlScrollbar(gump, geom): scroll = gump.addScrollArea(geom) scroll.marginLeft = 3 scroll.marginTop = 3 scroll.marginRight = 3 scroll.marginBottom = 3 scroll.vertical.width = 15 scroll.vertical.thumb.texture = Texture(TextureSource.GUMPART, 254) scroll.vertical.increment.texture = Texture(TextureSource.GUMPART, 253) scroll.vertical.incrementMouseDown.texture = Texture(TextureSource.GUMPART, 252) scroll.vertical.decrement.texture = Texture(TextureSource.GUMPART, 251) scroll.vertical.decrementMouseOver.texture = Texture(TextureSource.GUMPART, 250) scroll.vertical.track.texture = Texture(TextureSource.GUMPART, 255) scroll.updateScrollbars() return scroll
Python
# -*- coding: utf-8 -*- from ui import * from data import * import time def onButtonClick(button): print "onButtonClick" button.rgba = (1.0, 0.0, 1.0) print button.name button.halign = HAlign.RIGHT button.valign = VAlign.TOP button.gump.component("i1").hue = 90 print button.gump.store print button.gump.store["i2"] button.gump.store["i2"].rgba = rgba(91) button.gump.component("l2").halign = HAlign.RIGHT def create(args): g = GumpMenu("test", 30, 30) b1 = g.addBackground((0, 0, 500, 500), 3000) b1.rgba = rgba("#ff0000") # test for texture class i1 = g.addImage((0, 0, 100, 100), Texture(TextureSource.THEME, "images/button.png")) i1.texture = Texture(TextureSource.GUMPART, 13) i1.geometry = (30, 30) i1.hue = 13 i2 = g.addImage((0, 0), Texture(TextureSource.GUMPART, 12)) i2.rgba = (0.8, 0.2, 0.0) i2.alpha = 0.6 i2.hue = 2 but = g.addPythonButton((10, 10, 100, 60), Texture(TextureSource.THEME, "images/button.png"), onButtonClick) but.state("mouseOver").hue = 13 but.state("mouseDown").rgba = (1.0, 1.0, 0.0) but.text = "foooobert" but.state("mouseDown").fontRgba = rgba(4) but.state("mouseOver").fontRgba = rgba("#00ffff") but.setFont("Arial", 8); i1.name = "i1" g.store["i2"] = i2 # cliloc test str2 = Cliloc(501522) str3 = Cliloc(1072058, [ "fo", "awef" ]) print str2 print str3 g.addAlphaRegion((50, 50, 100, 100), 0.9) l1 = g.addLabel((300, 300), str2) l1.halign = HAlign.RIGHT l1.rgba = rgba(13) l2 = g.addLabel((5, 300, 200, 30), "centered") l2.halign = HAlign.CENTER l2.name = "l2"
Python
from ui import * from data import * import client import theme def create(args): g = GumpMenu("login", 387, 320) g.setFont("Devinne Swash", 16) g.onEnter = onGumpEnter g.onEscape = onGumpEscape g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_250x125.png")) label = g.addLabel((10, 15, 230, 80), args["message"]) label.halign = HAlign.CENTER btnClose = theme.addPythonButton(g, (60, 90, 130, 25), onClick) btnClose.text = "OK" def onClick(button): # returning true closes the gump return True def onGumpEnter(gump): gump.close() def onGumpEscape(gump): gump.close()
Python
from ui import * from data import * import theme import client import world def create(args): g = GumpMenu("skills", args.get("x", 100), args.get("y", 100)) g.mobile = args["mobile"] g.onPropertyUpdate = updateSkillValues g.addBackground((0, 0, 400, 400), 3000) scroll = theme.addScrollArea(g, (5, 5, 390, 390)) # list of tuples: # [0]: id # [1]: usable # [2]: name skills = getSkillList() yOffset = 0 for cur in skills: if (cur[1]): b = scroll.addPythonButton((1, 3 + yOffset), Texture(TextureSource.GUMPART, 2103), useSkill) b.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2104) b.store["skillid"] = cur[0] scroll.addLabel((15, 1 + yOffset, 180, 20), cur[2]) lValue = scroll.addLabel((200, 1 + yOffset, 80, 20), "") lValue.name = "lValue.%s" % cur[2] lBase = scroll.addLabel((290, 1 + yOffset, 80, 20), "") lBase.name = "lBase.%s" % cur[2] yOffset += 22 scroll.updateScrollbars() # init labels updateSkillValues(g) return g def useSkill(button): client.useSkill(button.store["skillid"]) return False def updateSkillValues(gump): # list of tuples: # [0]: id # [1]: usable # [2]: name skills = getSkillList() for cur in skills: valueTxt = "%s / %s" % (gump.mobile.getProperty("skills.%s.value" % cur[2]), gump.mobile.getProperty("skills.%s.cap" % cur[2])) gump.component("lValue.%s" % cur[2]).text = valueTxt baseTxt = "Base: %s" % (gump.mobile.getProperty("skills.%s.base" % cur[2])) gump.component("lBase.%s" % cur[2]).text = baseTxt def save(gump): saveData = { "x": gump.x, "y": gump.y, "serial": gump.mobile.serial } return saveData def load(saveData): mob = world.getMobile(saveData["serial"]) if mob: saveData["mobile"] = mob gump = create(saveData)
Python
from ui import * from data import * import client import theme #In case you want to redesign this gump, keep in mind that at this point, you can not #access any uo data (e.g. art.mul graphics, hues), as the mul files are not loaded yet. def create(args): g = GumpMenu("createshard", 400, 300) g.draggable = False g.onEnter = createShard theme.setFont(g) g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_350x190.png")) g.addLabel((15, 16), "Name:") g.addImage((115, 13, 220, 22), Texture(TextureSource.THEME, "images/lineedit_back.png")) le = g.addLineEdit((120, 15, 215, 20)) le.name = "shardname" g.addLabel((15, 46), "UO path:") g.addImage((115, 43, 220, 22), Texture(TextureSource.THEME, "images/lineedit_back.png")) le = g.addLineEdit((120, 45, 215, 20)) le.name = "uopath" cb = theme.addCheckbox(g, (15, 80)) cb.name = "highseas" g.addLabel((35, 80), "High seas") btnCreate = theme.addPythonButton(g, (30, 150, 130, 25), createShardButton) btnCreate.text = "Create shard" btnCancel = theme.addPythonButton(g, (190, 150, 130, 25), cancel) btnCancel.text = "Cancel" def createShardButton(btn): return createShard(btn.gump) def createShard(gump): if client.createShard(gump.component("shardname").text, gump.component("uopath").text, gump.component("highseas").checked): return True else: return False def cancel(_): # close gump return True
Python
import ui from data import * import world # mapping between the id sent by the server and the id in gumpart.mul BUFF_ICONS = { 0x3e9: 0x754C, 0x3ea: 0x754A, 0x3ed: 0x755E, 0x3ee: 0x7549, 0x3ef: 0x7551, 0x3f0: 0x7556, 0x3f1: 0x753A, 0x3f2: 0x754D, 0x3f3: 0x754E, 0x3f4: 0x7565, 0x3f5: 0x753B, 0x3f6: 0x7543, 0x3f7: 0x7544, 0x3f8: 0x7546, 0x3f9: 0x755C, 0x3fa: 0x755F, 0x3fb: 0x7556, 0x3fc: 0x7554, 0x3fd: 0x7540, 0x3fe: 0x7568, 0x3ff: 0x754F, 0x400: 0x7550, 0x401: 0x7553, 0x402: 0x753E, 0x403: 0x755D, 0x404: 0x7563, 0x405: 0x7562, 0x406: 0x753F, 0x407: 0x7559, 0x408: 0x7557, 0x409: 0x754B, 0x40a: 0x753D, 0x40b: 0x7561, 0x40c: 0x7558, 0x40d: 0x755B, 0x40e: 0x7560, 0x40f: 0x7541, 0x410: 0x7545, 0x411: 0x7552, 0x412: 0x7569, 0x413: 0x7548, 0x414: 0x755A, 0x415: 0x753C, 0x416: 0x7547, 0x417: 0x7567, 0x418: 0x7542, } def populateGump(g): bufflist = world.getPlayer().buffs g.addBackground((0, 0, len(bufflist) * 30 + 8, 36), 3000) x = 4 # bufflist is a list of tuples # (icon id, title, desc, seconds to expire) for cur in bufflist: if cur[0] in BUFF_ICONS: g.addImage((x, 4), Texture(TextureSource.GUMPART, BUFF_ICONS[cur[0]])) x += 30 else: print "Unknown buff icon", cur[0], cur[1] # TODO: do something with the description and title # TODO: display expire time def create(args): g = ui.GumpMenu("buffbar", args.get("x", 50), args.get("y", 50)) populateGump(g) def refreshBuffs(gump): gump.clearComponents() populateGump(gump)
Python
from ui import * from data import * import client def create(args): g = GumpMenu("gamewindow", args.get("x", 20), args.get("y", 20), True) g.closable = False g.onEnter = showSpeechEntry width = args.get("width", 800) height = args.get("height", 600) g.addPage(0) g.addBackground((0, 0, width + 10, height + 10), 2620) wv = g.addWorldView((5, 5, width, height)) wv.name = "worldview" syslog = g.addSysLogLabel((7, 7, 250, height - 40)) syslog.setFont("unifont1", 12, True) syslog.rgba = rgba("#dddddd") # default color # empty page to prevent the speech entry from being displayed at startup g.addPage(1) g.addPage(2) bg = g.addImage((5, 581, 608, 22), Texture(TextureSource.THEME, "images/solid.png")) bg.rgba = rgba("#dddddd33") speechEntry = g.addLineEdit((7, 583, 600, 20)) speechEntry.setFont("unifont1", 12) speechEntry.name = "speechentry" speechEntry.onEnter = sendSpeech return g def showSpeechEntry(gump): gump.page = 2 gump.component("speechentry").focus() def sendSpeech(entry): client.handleTextInput(entry.text) entry.text = "" entry.gump.page = 1 entry.gump.component("worldview").focus() def save(gump): saveData = { "x": gump.x, "y": gump.y, "width": gump.component("worldview").width, "height": gump.component("worldview").height, } # nothing specific to store return saveData def load(saveData): gump = create(saveData)
Python
import ui from data import Texture, TextureSource, rgba import client def create(args): g = ui.GumpMenu("spellbook", 100, 100) g.setFont("Devinne Swash", 16) g.addPage(0) g.addImage((0, 0), Texture(TextureSource.GUMPART, 2220)) # circle numbers g.addPageButton((58, 175), Texture(TextureSource.GUMPART, 2225), 1) g.addPageButton((92, 175), Texture(TextureSource.GUMPART, 2226), 1) g.addPageButton((129, 175), Texture(TextureSource.GUMPART, 2227), 2) g.addPageButton((164, 175), Texture(TextureSource.GUMPART, 2228), 2) g.addPageButton((227, 175), Texture(TextureSource.GUMPART, 2229), 3) g.addPageButton((260, 175), Texture(TextureSource.GUMPART, 2230), 3) g.addPageButton((297, 175), Texture(TextureSource.GUMPART, 2231), 4) g.addPageButton((332, 175), Texture(TextureSource.GUMPART, 2232), 4) # circles is a list of dictionaries, each dictionary holding a list of spells and infos about the circle: # circle["spells"]: list of spells # ["id"]: numerical id # ["name"]: name # each spell is a tuple # (id, name, wops, descriptionHeader, description, gumpid) # id: numerical id # name: name # wops: words of power # descriptionHeader: header text of the spell description # description: spell description # gumpid: spell icon id circles = args["circles"] page = 0 spellPage = 5 spellCount = 0 # circle overviews for circle in circles: if circle["id"] % 2 == 1: # left page page += 1 g.addPage(page) # flip back if page > 1: g.addPageButton((50, 8), Texture(TextureSource.GUMPART, 2235), page - 1) # flip forward g.addPageButton((321, 8), Texture(TextureSource.GUMPART, 2236), page + 1) addTitleLabel(g, (100, 14, 40, 15), "INDEX") addTitleLabel(g, (55, 34, 150, 15), circle["name"]) spellX = 55 else: # right page addTitleLabel(g, (267, 14, 40, 15), "INDEX") addTitleLabel(g, (223, 34, 150, 15), circle["name"]) spellX = 223 spellY = 50 for spell in circle["spells"]: l = addTextLabel(g, (spellX, spellY, 150, 15), spell[1]) l.page = spellPage # flip gump to this page if clicked spellCount += 1 if spellCount % 2 == 0: spellPage += 1 spellY += 15 spellPage = 5 spellCount = 0 x = 0 for circle in circles: for spell in circle["spells"]: if spellCount % 2 == 0: # add flip forward to previous page if spellCount > 1: g.addPageButton((321, 8), Texture(TextureSource.GUMPART, 2236), spellPage + 1) g.addPage(spellPage) # flip back g.addPageButton((50, 8), Texture(TextureSource.GUMPART, 2235), spellPage - 1) spellPage += 1 x = 0 # circle header for left page addTitleLabel(g, (x + 85, 14, 100, 15), circle["name"]) else: # circle header for right page addTitleLabel(g, (x + 65, 14, 100, 15), circle["name"]) # spell name addTitleLabel(g, (x + 105, 38, 90, 35), spell[1]) # description title addTitleLabel(g, (x + 55, 95, 150, 15), spell[3]) # description addTextLabel(g, (x + 55, 110, 150, 55), spell[4]) # spell icon btCast = g.addPythonButton((x + 55, 40), Texture(TextureSource.GUMPART, spell[5]), castSpell) btCast.store["spellid"] = spell[0] spellCount += 1 x += 168 args["item"].setSpellbookGump(g) def addTitleLabel(g, geom, text): l = g.addLabel(geom, text) l.rgba = rgba("#001052") return l def addTextLabel(g, geom, text): l = g.addLabel(geom, text) l.rgba = rgba("#5a4a31") return l def castSpell(button): client.castSpell(button.store["spellid"])
Python
from ui import * from data import * import client import world def create(args): g = GumpMenu("paperdoll", args.get("x", 50), args.get("y", 50)) g.mobile = args["mobile"] g.onWarmodeChanged = onWarmodeChanged g.addImage((0, 0), Texture(TextureSource.GUMPART, 2000)) g.addPaperdollView((3, 9, 240, 300), g.mobile) g.addPythonButton((20, 195), Texture(TextureSource.GUMPART, 2002), openProfile) if g.mobile == world.getPlayer(): btnHelp = g.addPythonButton((185, 44), Texture(TextureSource.GUMPART, 2031), sendHelpRequest) btnHelp.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2033) btnHelp.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2032) btnDisconnect = g.addPythonButton((185, 98), Texture(TextureSource.GUMPART, 2009), disconnect) btnDisconnect.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2011) btnDisconnect.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2010) btnSkills = g.addPythonButton((185, 154), Texture(TextureSource.GUMPART, 2015), openSkills) btnSkills.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2017) btnSkills.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2016) if g.mobile.warmode: btnWarmode = g.addPythonButton((185, 205), Texture(TextureSource.GUMPART, 2024), toggleWarmode) btnWarmode.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2026) btnWarmode.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2025) else: btnWarmode = g.addPythonButton((185, 205), Texture(TextureSource.GUMPART, 2021), toggleWarmode) btnWarmode.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2023) btnWarmode.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2022) btnWarmode.name = "btnWarmode" btStatus = g.addPythonButton((185, 233), Texture(TextureSource.GUMPART, 2027), openStatus) btStatus.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2029) btStatus.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2028) g.addPropertyLabel((20, 270, 180, 20), "paperdoll-name") return g def onWarmodeChanged(gump): btnWarmode = gump.component("btnWarmode") if gump.mobile.warmode: btnWarmode.texture = Texture(TextureSource.GUMPART, 2024) btnWarmode.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2026) btnWarmode.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2025) else: btnWarmode.texture = Texture(TextureSource.GUMPART, 2021) btnWarmode.state("mouseOver").texture = Texture(TextureSource.GUMPART, 2023) btnWarmode.state("mouseDown").texture = Texture(TextureSource.GUMPART, 2022) def openProfile(button): button.gump.mobile.openProfile() return False def sendHelpRequest(button): client.sendHelpRequest() return False def disconnect(button): client.disconnect() return False def openSkills(button): button.gump.mobile.openSkills() return False def toggleWarmode(button): mob = button.gump.mobile mob.warmode = not mob.warmode return False def openStatus(button): button.gump.mobile.openStatus() return False def save(gump): saveData = { "x": gump.x, "y": gump.y, # To be able to also restore the gump after a restart, save only the serial "serial": gump.mobile.serial } return saveData def load(saveData): mob = world.getMobile(saveData["serial"]) if mob: saveData["mobile"] = mob gump = create(saveData) # request paperdoll data from server saveData["mobile"].openPaperdoll()
Python
import ui import theme import client import data def create(args): g = ui.GumpMenu("objectpropertylist", args["x"], args["y"]) g.draggable = False g.closable = False g.addBackground((0, 0, 250, len(args["lines"]) * 16 + 10), 3000) y = 5 # lines is a list of strings for cur in args["lines"]: g.addLabel((5, y), cur) y += 16
Python
import ui import theme import client import data def create(args): g = ui.GumpMenu("contextmenu", 50, 50) g.draggable = False g.store["serial"] = args["serial"] y = 0 # entries is a list of tuples # (entry id, cliloc id) for cur in args["entries"]: bt = theme.addPythonButton(g, (0, y, 300, 25), onClick) bt.store["entryId"] = cur[0] bt.text = data.Cliloc(cur[1]) y += 25 def onClick(button): client.contextMenuReply(button.gump.store["serial"], button.store["entryId"]) return True
Python
from ui import * from data import * import world def create(args): g = GumpMenu("status", args.get("x", 100), args.get("y", 100)) g.mobile = args["mobile"] if g.mobile == world.getPlayer(): g.addImage((0, 0), Texture(TextureSource.GUMPART, 10860)) l = g.addPropertyLabel((83, 45, 295, 20), "name") l.halign = HAlign.CENTER l = g.addPropertyLabel((83, 73, 35, 25), "strength") l.halign = HAlign.CENTER l = g.addPropertyLabel((83, 102, 35, 25), "dexterity") l.halign = HAlign.CENTER l = g.addPropertyLabel((83, 129, 35, 25), "intelligence") l.halign = HAlign.CENTER l = g.addPropertyLabel((145, 69, 35, 20), "hitpoints") l.halign = HAlign.CENTER l = g.addPropertyLabel((145, 81, 35, 20), "hitpoints-max") l.halign = HAlign.CENTER l = g.addPropertyLabel((145, 94, 35, 20), "stamina") l.halign = HAlign.CENTER l = g.addPropertyLabel((145, 107, 35, 20), "stamina-max") l.halign = HAlign.CENTER l = g.addPropertyLabel((145, 122, 35, 20), "mana") l.halign = HAlign.CENTER l = g.addPropertyLabel((145, 135, 35, 20), "mana-max") l.halign = HAlign.CENTER l = g.addPropertyLabel((219, 74, 35, 20), "statcap") l.halign = HAlign.CENTER l = g.addPropertyLabel((219, 102, 35, 20), "luck") l.halign = HAlign.CENTER l = g.addPropertyLabel((219, 130, 35, 20), "weight") l.halign = HAlign.CENTER l = g.addPropertyLabel((281, 74, 35, 20), "damage-min") l.halign = HAlign.CENTER # TODO: damage max l = g.addPropertyLabel((281, 102, 35, 20), "gold") l.halign = HAlign.CENTER l = g.addPropertyLabel((281, 130, 35, 20), "followers") l.halign = HAlign.CENTER # TODO: followers max l = g.addPropertyLabel((352, 69, 35, 20), "resist-physical") l.halign = HAlign.CENTER l = g.addPropertyLabel((352, 85, 35, 20), "resist-fire") l.halign = HAlign.CENTER l = g.addPropertyLabel((352, 100, 35, 20), "resist-cold") l.halign = HAlign.CENTER l = g.addPropertyLabel((352, 116, 35, 20), "resist-poison") l.halign = HAlign.CENTER l = g.addPropertyLabel((352, 132, 35, 20), "resist-energy") l.halign = HAlign.CENTER l.rgba = rgba("#444444") #TODO: SE/SA Addons (Buttons for StatsUp/Down, BuffList-Button) else: # TODO: proper uo gump g.addBackground((0, 0, 250, 52), 3000) g.addPropertyLabel((5, 5, 250, 20), "name") g.addPropertyLabel((5, 22, 250, 20), "hitpoints") return g def save(gump): saveData = { "x": gump.x, "y": gump.y, # To be able to also restore the gump after a restart, save only the serial "serial": gump.mobile.serial } return saveData def load(saveData): mob = world.getMobile(saveData["serial"]) if mob: saveData["mobile"] = mob gump = create(saveData) # request status data from server saveData["mobile"].openStatus()
Python
import ui from data import Texture, TextureSource import client import theme def create(args): g = ui.GumpMenu("yesnobox", 300, 300) g.onEnter = choiceYes g.onEscape = choiceNo g.store["callbackYes"] = args["callbackYes"] g.store["callbackNo"] = args["callbackNo"] g.store["callbackArgs"] = args["callbackArgs"] g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_250x125.png")) question = g.addLabel((10, 15, 230, 80), args["question"]) question.halign = ui.HAlign.CENTER btYes = theme.addPythonButton(g, (20, 90, 80, 25), choiceYes) btYes.text = "Yes" btYes.store["callbackYes"] = args["callbackYes"] btYes.store["callbackArgs"] = args["callbackArgs"] btNo = theme.addPythonButton(g, (120, 90, 80, 25), choiceNo) btNo.text = "No" btNo.store["callbackNo"] = args["callbackNo"] btNo.store["callbackArgs"] = args["callbackArgs"] def choiceYes(obj): obj.store["callbackYes"](obj.store["callbackArgs"]) return True def choiceNo(obj): obj.store["callbackNo"](obj.store["callbackArgs"]) return True
Python
from world import * from ui import * from data import * import client import theme def create(args): g = GumpMenu("login", 337, 289, True) theme.setFont(g) g.closable = False g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_350x190.png")) g.addLabel((15, 16), "IP/Hostname:") g.addImage((115, 13, 220, 22), Texture(TextureSource.THEME, "images/lineedit_back.png")) le = g.addLineEdit((120, 15, 215, 20)) le.text = client.getConfig("/fluo/shard/address@host") le.name = "hostname" le.onEnter = connect g.addLabel((15, 46), "Port:") g.addImage((115, 43, 220, 22), Texture(TextureSource.THEME, "images/lineedit_back.png")) le = g.addLineEdit((120, 45, 215, 20)) le.numeric = True le.text = client.getConfig("/fluo/shard/address@port") le.name = "port" le.onEnter = connect g.addLabel((15, 76), "Account:") g.addImage((115, 73, 220, 22), Texture(TextureSource.THEME, "images/lineedit_back.png")) le = g.addLineEdit((120, 75, 215, 20)) le.text = client.getConfig("/fluo/shard/account@name") le.name = "account" le.onEnter = connect g.addLabel((15, 106), "Password:") g.addImage((115, 103, 220, 22), Texture(TextureSource.THEME, "images/lineedit_back.png")) le = g.addLineEdit((120, 105, 215, 20)) le.password = True le.text = client.getConfig("/fluo/shard/account@password") le.name = "password" le.onEnter = connect btnExit = theme.addPythonButton(g, (30, 150, 130, 25), shutdown) btnExit.text = "Exit" btnConnect = theme.addPythonButton(g, (190, 150, 130, 25), connect) btnConnect.text = "Connect" def shutdown(component): client.shutdown() def connect(component): g = component.gump if client.connect(g.component("hostname").text, int(g.component("port").text), g.component("account").text, g.component("password").text): return True else: client.messagebox("Could not connect to %s" % g.component("hostname").text) return False
Python
from data import * from ui import * import client import theme def create(args): g = GumpMenu("characterlist", 400, 300) g.closable = False charList = args["characterlist"] # characterlist is a list of tuples (index, name, password) if len(charList) > 0: g.onEnter = selectFirst g.store["index"] = charList[0][0] g.store["name"] = charList[0][1] g.store["password"] = charList[0][2] g.addImage((0, 0), Texture(TextureSource.THEME, "images/background_250x250.png")) scroll = theme.addScrollArea(g, (20, 20, 210, 137)) y = 0 for (idx, name, password) in charList: btnChar = theme.addPythonButton(scroll, (0, y, 160, 25), selectCharacter) btnChar.text = name btnChar.store["index"] = idx btnChar.store["name"] = name btnChar.store["password"] = password btnDel = theme.addPythonButton(scroll, (165, y, 25, 25), deleteCharacter) btnDel.store["index"] = idx btnDel.store["password"] = password btnDel.text = "X" y += 28 scroll.updateScrollbars() btnDummy = theme.addPythonButton(g, (20, 175, 210, 25), createDummyCharacter) btnDummy.text = "Create Dummy Character" btnDisconnect = theme.addPythonButton(g, (20, 203, 210, 25), disconnect) btnDisconnect.text = "Disconnect" def disconnect(button): client.disconnect() button.gump.close() return True def selectFirst(gump): client.selectCharacter(gump.store["index"], gump.store["name"], gump.store["password"]) gump.close() return True def selectCharacter(button): client.selectCharacter(button.store["index"], button.store["name"], button.store["password"]) button.gump.close() return True def createDummyCharacter(button): client.createDummyCharacter() button.gump.close() return True def deleteCharacter(button): callbackArgs = { "index": button.store["index"], "password": button.store["password"], "gump": button.gump, } args = { "callbackYes": deleteCharacter2, "callbackNo": cancelDelete, "callbackArgs": callbackArgs, "question": "Do you really want to delete this character?", } client.openGump("yesnobox", args) return False def deleteCharacter2(args): client.deleteCharacter(args["index"], args["password"]) def cancelDelete(args): pass
Python
import ui import world def create(args): g = ui.GumpMenu("container", args.get("x", 100), args.get("y", 100)) cont = g.addContainerView((0, 0), args["item"]) cont.background = args["background"] g.store["serial"] = args["item"].serial g.store["background"] = args["background"] def save(gump): saveData = { "x": gump.x, "y": gump.y, # To be able to also restore the gump after a restart, save only the serial "serial": gump.store["serial"], "background": gump.store["background"], } return saveData def load(saveData): itm = world.getDynamicItem(saveData["serial"]) if itm: saveData["item"] = itm gump = create(saveData)
Python
from ui import * from data import * import client def create(args): g = GumpMenu("minimap", args.get("x", 120), args.get("y", 120)) width = args.get("width", 300) height = args.get("height", 300) g.addBackground((0, 0, width + 6, height + 6), 2620) mmv = g.addMiniMapView((3, 3, width, height)) mmv.name = "minimap" return g def save(gump): saveData = { "x": gump.x, "y": gump.y, } # nothing specific to store return saveData def load(saveData): gump = create(saveData)
Python
# this gump is opened after receiving packet 0x7C and can be either # just a question or a gump to pick an item from ui import * from data import * import client import theme def create(args): g = GumpMenu("", 250, 150) g.store["serial"] = args["serial"] # to be included in the response g.store["menuid"] = args["menuid"] # to be included in the response g.addBackground((0, 0, 250, 300), 3000) title = g.addLabel((5, 7, 240, 20), args["question"]) title.halign = HAlign.CENTER scroll = theme.addScrollArea(g, (5, 30, 240, 265)) # args["answers"] is a list of tuples # (answerid, text, artid, hue) y = 0 for answer in args["answers"]: if answer[2] == 0: # question only btText = theme.addPythonButton(scroll, (5, y + 5, 210, 25), onButtonClick) btText.store["data"] = answer btText.text = answer[1] else: # display art texture btArt = scroll.addPythonButton((5, y + 5), Texture(TextureSource.STATICART, answer[2]), onButtonClick) btArt.store["data"] = answer btArt.hue = answer[3] scroll.addLabel((50, y + 10), answer[1]) y += 28 scroll.updateScrollbars() return g def onButtonClick(button): client.objectPickerResponse(button.gump.store["serial"], button.gump.store["menuid"], button.store["data"][0], button.store["data"][2], button.store["data"][3]) return True
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
from django.db import models
Python
# Create your views here.
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', # Example: # (r'^fluidmeets/', include('fluidmeets.foo.urls')), # Uncomment this for admin: (r'^admin/', include('django.contrib.admin.urls')), )
Python
# Django settings for fluidmeets project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ('Sebastian Castillo Builes', 'castillobuiles@gmail.com'), ('Rafael S. Gonzalez D\'Leon', 'rafaeldleon@gmail.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_NAME = 'fluidmeets.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE # although not all variations may be possible on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Bogota' # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '3rwl2co_(eottkn=4zogh7v0$-82mzb@_%yk#npoga-)1gnf9k' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', ) ROOT_URLCONF = 'fluidmeets.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', )
Python
#!/usr/bin/env python import errno import os import pexpect import re import string import threading import time import pygtk import gobject import gtk import gtk.glade class UnisonProfile: treestore = gtk.ListStore(str) def __init__(self): self.treestore.append(['fluence-test']) pass def save(self): try: os.mkdir("/home/wlach/.unison") except OSError, e: # Ignore directory exists error if e.errno <> errno.EEXIST: raise proffile = open(os.path.join("/home/wlach/.unison", "fluence.prf"), 'w') proffile.write("# This file has been automatically generated by " "fluence: DO NOT EDIT!\n") proffile.write("root = /home/wlach/\n") proffile.write("root = /tmp/wlach/\n") proffile.write("\n") row = self.treestore.get_iter_first() while row: print "Adding path: " + self.treestore[row][0] proffile.write("path = " + self.treestore[row][0] + "\n") row = self.treestore.iter_next(row) proffile.write("\n"); proffile.close() class SyncWindow: def __init__(self, mainwindow): self.dialog = gtk.Dialog("Synchronizing files", mainwindow, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)) self.dialog.set_property("has-separator", False) title_label = gtk.Label() title_label.set_markup("<big><b>Synchronizing files</b></big>") title_label.set_alignment(0, 0) title_label.set_padding(8, 8) from_label = gtk.Label() from_label.set_markup("<b>From:</b> " "foo") from_label.set_alignment(0, 0) from_label.set_padding(8, 2) to_label = gtk.Label() to_label.set_markup("<b>To:</b> " "foo") to_label.set_alignment(0, 0) to_label.set_padding(8, 2) self.progressbar = gtk.ProgressBar() #self.progressbar.set_text("Synchronizing file: x of y (0:00 remaining)") progress_align = gtk.Alignment(1, 1, 1, 1) progress_align.set_padding(2, 2, 8, 8) progress_align.add_with_properties(self.progressbar) self.dialog.vbox.pack_start(title_label, True) self.dialog.vbox.pack_start(from_label, False) self.dialog.vbox.pack_start(to_label, False) self.dialog.vbox.pack_start(progress_align, False) def destroy_soon_cb(self): self.dialog.destroy() return False def destroy_soon(self): gobject.timeout_add(2000, self.destroy_soon_cb) def show(self): self.dialog.show_all() class Synchronizer(threading.Thread): def __init__(self, syncwindow): threading.Thread.__init__(self) self.syncwindow = syncwindow pass def run(self): # control here should pass to a thread.. self.unison = pexpect.spawn('unison -batch fluence') print "Syncing.." self.percent = 0.0 # read one byte at a time.. self.line = '' while self.poll_child(): pass self.syncwindow.destroy_soon() def update_progress(self, percent): #print "Updating progress.." + str(float(self.counter)/100000.0) self.syncwindow.progressbar.set_fraction(percent/100.0) return False def poll_child(self): try: l = self.unison.read_nonblocking(1, 0) if l == '\r' or l == '\n': print "READ: " + self.line m = re.search('(\d+)%', self.line) if m: percent = float(m.group(1)) gobject.idle_add(self.update_progress, percent) print "Match found in line: " + str(percent) elif re.search('Nothing to do: replicas have not changed ' + 'since last sync.', self.line): percent = 100.0 gobject.idle_add(self.update_progress, percent) else: print "No match" self.line = '' else: self.line += l return 1 except pexpect.EOF: return 0 except pexpect.TIMEOUT: return 1 class MainWindow: def __init__(self): # create a new window self.xml = gtk.glade.XML("mainwindow.glade") self.dialog = self.xml.get_widget("mainwindow") self.dialog.connect ("destroy", gtk.main_quit) #self.dialog.set_default_response (gtk.RESPONSE_ACCEPT) # folders in a unison profile self.uprofile = UnisonProfile() self.folderview = self.xml.get_widget("folderview") column = gtk.TreeViewColumn ("Folders", gtk.CellRendererText(), text=0) self.folderview.append_column (column) self.folderview.set_model(self.uprofile.treestore) # the button to add a folder self.add_folder_button = self.xml.get_widget("addfolder") self.add_folder_button.connect("clicked", self.__add_folder_button_clicked) # the button to synchronize self.xml.get_widget("syncbutton").connect("clicked", self.__sync_button_clicked) # and the window self.dialog.show_all() def __add_folder_button_clicked(self, button): filechooser = gtk.FileChooserDialog("Add folder", self.dialog, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT)) response = filechooser.run() if response == gtk.RESPONSE_ACCEPT: m = re.search('file:///home/wlach/(.*)', filechooser.get_uri()) if m: self.uprofile.treestore.append([m.group(1)]) else: print "Invalid URI!!" filechooser.destroy() def __sync_button_clicked(self, button): print "Sync button clicked!" self.uprofile.save() print "Created syncwindow" self.syncwindow = SyncWindow(self.dialog) print "Creating synchronizer" self.synchronizer = Synchronizer(self.syncwindow) self.synchronizer.start() print "Created synchronizer" self.syncwindow.show() print "Syncwindow on display" def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main() if __name__ == "__main__": gobject.threads_init() mainwindow = MainWindow() mainwindow.main()
Python
#!/usr/bin/env python import errno import os import pexpect import re import string import threading import time import pygtk import gobject import gtk import gtk.glade class UnisonProfile: treestore = gtk.ListStore(str) def __init__(self): self.treestore.append(['fluence-test']) pass def save(self): try: os.mkdir("/home/wlach/.unison") except OSError, e: # Ignore directory exists error if e.errno <> errno.EEXIST: raise proffile = open(os.path.join("/home/wlach/.unison", "fluence.prf"), 'w') proffile.write("# This file has been automatically generated by " "fluence: DO NOT EDIT!\n") proffile.write("root = /home/wlach/\n") proffile.write("root = /tmp/wlach/\n") proffile.write("\n") row = self.treestore.get_iter_first() while row: print "Adding path: " + self.treestore[row][0] proffile.write("path = " + self.treestore[row][0] + "\n") row = self.treestore.iter_next(row) proffile.write("\n"); proffile.close() class SyncWindow: def __init__(self, mainwindow): self.dialog = gtk.Dialog("Synchronizing files", mainwindow, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)) self.dialog.set_property("has-separator", False) title_label = gtk.Label() title_label.set_markup("<big><b>Synchronizing files</b></big>") title_label.set_alignment(0, 0) title_label.set_padding(8, 8) from_label = gtk.Label() from_label.set_markup("<b>From:</b> " "foo") from_label.set_alignment(0, 0) from_label.set_padding(8, 2) to_label = gtk.Label() to_label.set_markup("<b>To:</b> " "foo") to_label.set_alignment(0, 0) to_label.set_padding(8, 2) self.progressbar = gtk.ProgressBar() #self.progressbar.set_text("Synchronizing file: x of y (0:00 remaining)") progress_align = gtk.Alignment(1, 1, 1, 1) progress_align.set_padding(2, 2, 8, 8) progress_align.add_with_properties(self.progressbar) self.dialog.vbox.pack_start(title_label, True) self.dialog.vbox.pack_start(from_label, False) self.dialog.vbox.pack_start(to_label, False) self.dialog.vbox.pack_start(progress_align, False) def destroy_soon_cb(self): self.dialog.destroy() return False def destroy_soon(self): gobject.timeout_add(2000, self.destroy_soon_cb) def show(self): self.dialog.show_all() class Synchronizer(threading.Thread): def __init__(self, syncwindow): threading.Thread.__init__(self) self.syncwindow = syncwindow pass def run(self): # control here should pass to a thread.. self.unison = pexpect.spawn('unison -batch fluence') print "Syncing.." self.percent = 0.0 # read one byte at a time.. self.line = '' while self.poll_child(): pass self.syncwindow.destroy_soon() def update_progress(self, percent): #print "Updating progress.." + str(float(self.counter)/100000.0) self.syncwindow.progressbar.set_fraction(percent/100.0) return False def poll_child(self): try: l = self.unison.read_nonblocking(1, 0) if l == '\r' or l == '\n': print "READ: " + self.line m = re.search('(\d+)%', self.line) if m: percent = float(m.group(1)) gobject.idle_add(self.update_progress, percent) print "Match found in line: " + str(percent) elif re.search('Nothing to do: replicas have not changed ' + 'since last sync.', self.line): percent = 100.0 gobject.idle_add(self.update_progress, percent) else: print "No match" self.line = '' else: self.line += l return 1 except pexpect.EOF: return 0 except pexpect.TIMEOUT: return 1 class MainWindow: def __init__(self): # create a new window self.xml = gtk.glade.XML("mainwindow.glade") self.dialog = self.xml.get_widget("mainwindow") self.dialog.connect ("destroy", gtk.main_quit) #self.dialog.set_default_response (gtk.RESPONSE_ACCEPT) # folders in a unison profile self.uprofile = UnisonProfile() self.folderview = self.xml.get_widget("folderview") column = gtk.TreeViewColumn ("Folders", gtk.CellRendererText(), text=0) self.folderview.append_column (column) self.folderview.set_model(self.uprofile.treestore) # the button to add a folder self.add_folder_button = self.xml.get_widget("addfolder") self.add_folder_button.connect("clicked", self.__add_folder_button_clicked) # the button to synchronize self.xml.get_widget("syncbutton").connect("clicked", self.__sync_button_clicked) # and the window self.dialog.show_all() def __add_folder_button_clicked(self, button): filechooser = gtk.FileChooserDialog("Add folder", self.dialog, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT)) response = filechooser.run() if response == gtk.RESPONSE_ACCEPT: m = re.search('file:///home/wlach/(.*)', filechooser.get_uri()) if m: self.uprofile.treestore.append([m.group(1)]) else: print "Invalid URI!!" filechooser.destroy() def __sync_button_clicked(self, button): print "Sync button clicked!" self.uprofile.save() print "Created syncwindow" self.syncwindow = SyncWindow(self.dialog) print "Creating synchronizer" self.synchronizer = Synchronizer(self.syncwindow) self.synchronizer.start() print "Created synchronizer" self.syncwindow.show() print "Syncwindow on display" def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main() if __name__ == "__main__": gobject.threads_init() mainwindow = MainWindow() mainwindow.main()
Python
#!/usr/bin/python """ File: manager.py ICS 413 Project Description: the Basic function of a schleduing calendar. A note on the dateList Structure: dateList[0] is the tuple of the first day. dateList[0][0] is the actual date value of the first day. (DateTuples) dateList[0][1] is the event list of the first day. (DateTuples) dateList[0][1][0] is the first event of the first day. (Entry) dateList[1] the tuple of the second day """ from datetime import date from datetime import time import datetime import os class manager(object): """Class that manages the calendar""" #dateList essentially is the calendar #takes on the form of: #[[date(2007, 7, 20), [1, 2, 3]], [date(2007, 7, 21), [1, 2, 3, 4]], [date(2007, 7, 22), [1, 2]]] # where the lists of numbers([1, 2, 3]) represent lists of to-do items for the corresponding day dateList = [] def __init__(self): print 'new manager class instantiated' def __add__(self, other): if type(other) is not entry: print "ERROR, cannot add anything but an entry to a manager" else: temp = self.addEntry(other.title, other.date) self.editEntry(temp, other.title, other.location, other.time, other.duration) if other.isComplete is True: self.complete(temp) def addEntry(self, title, date): #Adds a new entry to a Calendar list """Adds the entry to the daylist""" newEntry = entry(title, date) if (type(title) is not str) or (type(date) is not datetime.date): print 'Invalid entry: must have title' newEntry = None else: if len(self.dateList) == 0: #If there is nothing in the calendar yet subList = [newEntry.date, [newEntry]] #Add the first date and it's first entry self.dateList.append(subList) else: for i in range(len(self.dateList)): #i indexes each date #print self.dateList[i][0], "<-->", newEntry.date if self.dateList[i][0] == newEntry.date: #If the new entry is of an indexed date self.dateList[i][1].append(newEntry) #Add the entry to the end of the list for that day break elif self.dateList[i][0] > newEntry.date: #If the new entry comes before an indexed date subList = [newEntry.date, [newEntry]] #Insert the new day and it's 1st entry self.dateList.insert(i, subList) break elif i == (len(self.dateList)-1): #If the new entry comes after all indexed dates subList = [newEntry.date, [newEntry]] #Add the new day and it's 1st entry to the end self.dateList.append(subList) break print 'entry', newEntry.title, 'added' return newEntry def editEntry(self, tEntry, newTitle, newLocation, newTime, newDuration): """edits specified entry in the list""" for i in range(len(self.dateList)): if self.dateList[i][0] == tEntry.date: for j in range(len(self.dateList[i][1])): if self.dateList[i][1][j] == tEntry: #edit entry if entry not null(none) if newTitle is not None: tEntry.title = newTitle if newLocation is not None: tEntry.location = newLocation if newTime is not None: tEntry.time = newTime if newDuration is not None: tEntry.duration = newDuration print 'entry', tEntry.title, 'edited' break elif i == (len(self.dateList)-1): print 'entry', tEntry.title, 'not found' break #print "First Entry: ", self.dateList[0][1][0].title, "at", self.dateList[0][1][0].time self.sort(tEntry.date) return tEntry def removeEntry(self, rmEntry): """Removes Entry""" if type(rmEntry) is not entry: print 'ERROR, must pass an entry instance' else: for i in range(len(self.dateList)): if self.dateList[i][0] == rmEntry.date: for j in range(len(self.dateList[i][1])): if self.dateList[i][1][j] == rmEntry: self.dateList[i][1].remove(rmEntry) if len(self.dateList[i][1]) == 0: self.dateList.remove(self.dateList[i]) print 'entry deleted' def sort(self, date): """Sorts The Datelist by their time""" if type(date) is not datetime.date: print 'ERROR, must pass a date to sort' else: for x in self.dateList: if x[0] == date: if len(x[1]) is 1: break for y in range(1, len(x[1])): for i in range(len(x[1])-y): j = i + 1 #if ((x[1][i].time is None) and (x[1][j].time is not None)) #or ((x[1][i].location is None) and (x[1][j].location is not None)) #or (((x[1][i].time and x[1][j].time) is not None) #and (x[1][i].time > x[1][j].time)): if x[1][i] > x[1][j]: temp = x[1][j] x[1][j] = x[1][i] x[1][i] = temp break elif x[0] < date: print "ERROR, no entries exist for that date" print 'list re-sorted' #print "First Entry: ", self.dateList[0][1][0].title, "at", self.dateList[0][1][0].time def complete(self, entry): """Tells the user if a task is completed""" a = 'task not found' for i in range(len(self.dateList)): if self.dateList[i][0] == entry.date: for j in range(len(self.dateList[i][1])): if self.dateList[i][1][j] is entry: self.dateList[i][1][j].isComplete = True a = 'task completed' break break print a def export(self, target): """Function that gets the floydcal data ready to be wirtten into an *.ics file format""" mkTrunk = True print os.getcwd() for f in os.listdir(os.getcwd() + '/'): if f == 'floydcal': mkTrunk = False if mkTrunk: os.mkdir('floydcal') targetDate = None if type(target) is entry: targetDate = target.date elif type(target) is date: targetDate = target else: print "ERROR, wrong datatype passed" yearString = str(targetDate.year) monthString = str(targetDate.month) dayString = str(targetDate.day) mkYear = True mkMonth = True mkDay = True for f in os.listdir('floydcal'): if f == yearString: mkYear = False for g in os.listdir('floydcal/'+yearString): if g == monthString: mkMonth = False for h in os.listdir('floydcal/'+yearString+'/'+monthString): if h == dayString: mkDay = False break break break if mkYear: os.mkdir('floydcal/'+yearString) if mkMonth: os.mkdir('floydcal/'+yearString+'/'+monthString) if mkDay: os.mkdir('floydcal/'+yearString+'/'+monthString+'/'+dayString) path = os.getcwd()+'/floydcal/'+yearString+'/'+monthString+'/'+dayString if type(target) is entry: self.exportEntry(target, path) elif type(target) is date: for x in self.dateList: if x[0] == target: for y in x[1]: self.exportEntry(y, path) break print 'entry saved' def exportEntry(self, entry, path): """Function that writes every entry into a *.ics file""" apNum = '' num = 0 for i in os.listdir(path): if (entry.title+apNum+'.ics') == i: num+=1 apNum = str(num) beginDateString = str(entry.date.year)+str(entry.date.month)+str(entry.date.day) endDateString = beginDateString if entry.time is not None: beginDateString = beginDateString+"T"+str(entry.time.hour)+str(entry.time.minute)+'00' if entry.duration is not None: hour = entry.time.hour min = entry.time.minute deltaHrs = entry.duration/60 deltaMin = entry.duration - (deltaHrs*60) hour += deltaHrs min += deltaMin endDateString = endDateString +"T"+str(hour)+str(min)+'00' k = file(path+'/'+entry.title+apNum+'.ics', 'w') k.write("BEGIN:VCALENDAR\n") k.write("BEGIN:VTIMEZONE\n") k.write("TZID:Pacific/Honolulu\n") k.write("BEGIN:STANDARD\n") k.write("TZNAME:HST\n") k.write("END:STANDARD\n") k.write("END:VTIMEZONE\n") k.write("BEGIN:VEVENT\n") k.write("DTSTART:"+beginDateString+"\n") #begin date/time k.write("DTEND:"+endDateString+"\n") #end if entry.title is not None: k.write("SUMMARY:"+entry.title+"\n") if entry.location is not None: k.write("LOCATION:"+entry.location+"\n") k.write("END:VEVENT\n") k.write("END:VCALENDAR") k.close() class entry(object): "A basic to-do entry" title = None date = None location = None time = None isComplete = None duration = None def __init__(self, initTitle, initDate): self.title = initTitle self.date = initDate self.isComplete = False #defines the greater-than relationship between any two entries # entries with no time or location (tasks) are the greatest, all tasks are equal # entries with time (events) are the least, events are comparable by time # entries with location and no time (errands) fall between, all errands are equal def __gt__(self, other): value = None if type(other) is not entry: print "ERROR! The second value is not an entry" else: if ((self.time is None) and (other.time is not None)) or ((self.time is None) and (self.location is None) and (other.location is not None)) or (((self.time is not None) and (other.time is not None)) and (self.time > other.time)): value = True else: value = False return value
Python
#!/usr/bin/python """ File: manager.py ICS 413 Project Description: the Basic function of a schleduing calendar. A note on the dateList Structure: dateList[0] is the tuple of the first day. dateList[0][0] is the actual date value of the first day. (DateTuples) dateList[0][1] is the event list of the first day. (DateTuples) dateList[0][1][0] is the first event of the first day. (Entry) dateList[1] the tuple of the second day """ from datetime import date from datetime import time import datetime import os class manager(object): """Class that manages the calendar""" #dateList essentially is the calendar #takes on the form of: #[[date(2007, 7, 20), [1, 2, 3]], [date(2007, 7, 21), [1, 2, 3, 4]], [date(2007, 7, 22), [1, 2]]] # where the lists of numbers([1, 2, 3]) represent lists of to-do items for the corresponding day dateList = [] def __init__(self): print 'new manager class instantiated' def __add__(self, other): if type(other) is not entry: print "ERROR, cannot add anything but an entry to a manager" else: temp = self.addEntry(other.title, other.date) self.editEntry(temp, other.title, other.location, other.time, other.duration) if other.isComplete is True: self.complete(temp) def addEntry(self, title, date): #Adds a new entry to a Calendar list """Adds the entry to the daylist""" newEntry = entry(title, date) if (type(title) is not str) or (type(date) is not datetime.date): print 'Invalid entry: must have title' newEntry = None else: if len(self.dateList) == 0: #If there is nothing in the calendar yet subList = [newEntry.date, [newEntry]] #Add the first date and it's first entry self.dateList.append(subList) else: for i in range(len(self.dateList)): #i indexes each date #print self.dateList[i][0], "<-->", newEntry.date if self.dateList[i][0] == newEntry.date: #If the new entry is of an indexed date self.dateList[i][1].append(newEntry) #Add the entry to the end of the list for that day break elif self.dateList[i][0] > newEntry.date: #If the new entry comes before an indexed date subList = [newEntry.date, [newEntry]] #Insert the new day and it's 1st entry self.dateList.insert(i, subList) break elif i == (len(self.dateList)-1): #If the new entry comes after all indexed dates subList = [newEntry.date, [newEntry]] #Add the new day and it's 1st entry to the end self.dateList.append(subList) break print 'entry', newEntry.title, 'added' return newEntry def editEntry(self, tEntry, newTitle, newLocation, newTime, newDuration): """edits specified entry in the list""" for i in range(len(self.dateList)): if self.dateList[i][0] == tEntry.date: for j in range(len(self.dateList[i][1])): if self.dateList[i][1][j] == tEntry: #edit entry if entry not null(none) if newTitle is not None: tEntry.title = newTitle if newLocation is not None: tEntry.location = newLocation if newTime is not None: tEntry.time = newTime if newDuration is not None: tEntry.duration = newDuration print 'entry', tEntry.title, 'edited' break elif i == (len(self.dateList)-1): print 'entry', tEntry.title, 'not found' break #print "First Entry: ", self.dateList[0][1][0].title, "at", self.dateList[0][1][0].time self.sort(tEntry.date) return tEntry def removeEntry(self, rmEntry): """Removes Entry""" if type(rmEntry) is not entry: print 'ERROR, must pass an entry instance' else: for i in range(len(self.dateList)): if self.dateList[i][0] == rmEntry.date: for j in range(len(self.dateList[i][1])): if self.dateList[i][1][j] == rmEntry: self.dateList[i][1].remove(rmEntry) if len(self.dateList[i][1]) == 0: self.dateList.remove(self.dateList[i]) print 'entry deleted' def sort(self, date): """Sorts The Datelist by their time""" if type(date) is not datetime.date: print 'ERROR, must pass a date to sort' else: for x in self.dateList: if x[0] == date: if len(x[1]) is 1: break for y in range(1, len(x[1])): for i in range(len(x[1])-y): j = i + 1 #if ((x[1][i].time is None) and (x[1][j].time is not None)) #or ((x[1][i].location is None) and (x[1][j].location is not None)) #or (((x[1][i].time and x[1][j].time) is not None) #and (x[1][i].time > x[1][j].time)): if x[1][i] > x[1][j]: temp = x[1][j] x[1][j] = x[1][i] x[1][i] = temp break elif x[0] < date: print "ERROR, no entries exist for that date" print 'list re-sorted' #print "First Entry: ", self.dateList[0][1][0].title, "at", self.dateList[0][1][0].time def complete(self, entry): """Tells the user if a task is completed""" a = 'task not found' for i in range(len(self.dateList)): if self.dateList[i][0] == entry.date: for j in range(len(self.dateList[i][1])): if self.dateList[i][1][j] is entry: self.dateList[i][1][j].isComplete = True a = 'task completed' break break print a def export(self, target): """Function that gets the floydcal data ready to be wirtten into an *.ics file format""" mkTrunk = True print os.getcwd() for f in os.listdir(os.getcwd() + '/'): if f == 'floydcal': mkTrunk = False if mkTrunk: os.mkdir('floydcal') targetDate = None if type(target) is entry: targetDate = target.date elif type(target) is date: targetDate = target else: print "ERROR, wrong datatype passed" yearString = str(targetDate.year) monthString = str(targetDate.month) dayString = str(targetDate.day) mkYear = True mkMonth = True mkDay = True for f in os.listdir('floydcal'): if f == yearString: mkYear = False for g in os.listdir('floydcal/'+yearString): if g == monthString: mkMonth = False for h in os.listdir('floydcal/'+yearString+'/'+monthString): if h == dayString: mkDay = False break break break if mkYear: os.mkdir('floydcal/'+yearString) if mkMonth: os.mkdir('floydcal/'+yearString+'/'+monthString) if mkDay: os.mkdir('floydcal/'+yearString+'/'+monthString+'/'+dayString) path = os.getcwd()+'/floydcal/'+yearString+'/'+monthString+'/'+dayString if type(target) is entry: self.exportEntry(target, path) elif type(target) is date: for x in self.dateList: if x[0] == target: for y in x[1]: self.exportEntry(y, path) break print 'entry saved' def exportEntry(self, entry, path): """Function that writes every entry into a *.ics file""" apNum = '' num = 0 for i in os.listdir(path): if (entry.title+apNum+'.ics') == i: num+=1 apNum = str(num) beginDateString = str(entry.date.year)+str(entry.date.month)+str(entry.date.day) endDateString = beginDateString if entry.time is not None: beginDateString = beginDateString+"T"+str(entry.time.hour)+str(entry.time.minute)+'00' if entry.duration is not None: hour = entry.time.hour min = entry.time.minute deltaHrs = entry.duration/60 deltaMin = entry.duration - (deltaHrs*60) hour += deltaHrs min += deltaMin endDateString = endDateString +"T"+str(hour)+str(min)+'00' k = file(path+'/'+entry.title+apNum+'.ics', 'w') k.write("BEGIN:VCALENDAR\n") k.write("BEGIN:VTIMEZONE\n") k.write("TZID:Pacific/Honolulu\n") k.write("BEGIN:STANDARD\n") k.write("TZNAME:HST\n") k.write("END:STANDARD\n") k.write("END:VTIMEZONE\n") k.write("BEGIN:VEVENT\n") k.write("DTSTART:"+beginDateString+"\n") #begin date/time k.write("DTEND:"+endDateString+"\n") #end if entry.title is not None: k.write("SUMMARY:"+entry.title+"\n") if entry.location is not None: k.write("LOCATION:"+entry.location+"\n") k.write("END:VEVENT\n") k.write("END:VCALENDAR") k.close() class entry(object): "A basic to-do entry" title = None date = None location = None time = None isComplete = None duration = None def __init__(self, initTitle, initDate): self.title = initTitle self.date = initDate self.isComplete = False #defines the greater-than relationship between any two entries # entries with no time or location (tasks) are the greatest, all tasks are equal # entries with time (events) are the least, events are comparable by time # entries with location and no time (errands) fall between, all errands are equal def __gt__(self, other): value = None if type(other) is not entry: print "ERROR! The second value is not an entry" else: if ((self.time is None) and (other.time is not None)) or ((self.time is None) and (self.location is None) and (other.location is not None)) or (((self.time is not None) and (other.time is not None)) and (self.time > other.time)): value = True else: value = False return value
Python
import FonctionSetCover as F import Producteur as P import Set as S import Consommateur as C TabClient=[] TabProd=[] TabProd.append(P.Producteur("P1","Belleville-sur-Loire",47.506113,2.851424,30.9,1122612,0,10)) TabProd.append(P.Producteur("P2","Braud-et-Saint-Louis",45.248611,-0.623889,30.9,979534,0,10)) TabProd.append(P.Producteur("P3","Saint-Vulbas",45.8339,5.2931,30.9,665863,0,10)) TabProd.append(P.Producteur("P4","Cattenom",49.4067,6.2456,30.9,5090275,0,10)) TabProd.append(P.Producteur("P5","Avoine",47.205833,0.183889,30.9,4925185,0,10)) TabProd.append(P.Producteur("P6","Chooz",50.1042,4.8078,30.9,467755,0,10)) TabProd.append(P.Producteur("P7","Civaux",46.445278,0.666944,30.9,126569,0,10)) TabProd.append(P.Producteur("P8","Cruas",44.657778,4.763611,30.9,126569,0,10)) TabProd.append(P.Producteur("P9","Dampierre-en-Burly",47.760833,2.518333,30.9,126569,0,10)) TabProd.append(P.Producteur("P10","Fessenheim",47.9156,7.5367,30.9,126569,0,10)) TabProd.append(P.Producteur("P11","Flamanville",49.531389,-1.865278,30.9,126569,0,10)) TabProd.append(P.Producteur("P12","Golfech",44.114722,0.851944,30.9,126569,0,10)) TabProd.append(P.Producteur("P13","Gravelines",50.9858,2.1283,30.9,126569,0,10)) TabProd.append(P.Producteur("P14","Nogent-sur-Seine",48.494167,3.503333,30.9,126569,0,10)) TabProd.append(P.Producteur("P15","Paluel",49.8336,0.6289,30.9,126569,0,10)) TabProd.append(P.Producteur("P16","Saint-Martin-en-Campagne",49.957778,1.2225,30.9,126569,0,10)) TabProd.append(P.Producteur("P17","Saint-Alban-du-Rhone",45.4275,4.756111,30.9,126569,0,10)) TabProd.append(P.Producteur("P18","Saint-Laurent-Nouan",47.7175,1.6125,30.9,126569,0,10)) TabProd.append(P.Producteur("P19","Pierrelatte",44.378333,4.696389,30.9,126569,0,10)) TabClient.append(C.Consommateur(0.837758041,0.0523598776,"Paris","Ile-de-France",22234105,1667557875)) TabClient.append(C.Consommateur(0.7504915784,0,"Marseille","Provence-Alpes-Cote dAzur",850602,63795150)) TabClient.append(C.Consommateur(0.7853981634,0.0523598776,"Lyon","Rhone-Alpes",479803,35985225)) TabClient.append(C.Consommateur(0.7504915784,0.0174532925,"Toulouse","Midi-Pyrenees",440204,33015300)) TabClient.append(C.Consommateur(0.7504915784,0.0698131701,"Nice","Provence-Alpes-Cete dAzur",340735,25555125)) TabClient.append(C.Consommateur(0.8203047484,0,"Nantes","Pays de la Loire",282047,21153525)) TabClient.append(C.Consommateur(0.837758041,0.0698131701,"Strasbourg","Alsace",271708,20378100)) TabClient.append(C.Consommateur(0.7504915784,0.0872664626,"Montpellier","Languedoc-Roussillon",255080,19131000)) TabClient.append(C.Consommateur(0.7679448709,0.0872664626,"Bordeaux","Aquitaine",236725,17754375)) TabClient.append(C.Consommateur(0.872664626,0.0872664626,"Lille","Nord-Pas-de-Calais",226827,17012025)) TabClient.append(C.Consommateur(0.837758041,0,"Rennes","Bretagne",206604,15495300)) TabClient.append(C.Consommateur(0.8552113335,0.0698131701,"Reims","Champagne-Ardenne",180842,13563150)) TabClient.append(C.Consommateur(0.8552113335,0,"Le Havre","Haute-Normandie",177259,13294425)) TabClient.append(C.Consommateur(0.7853981634,0.0872664626,"Saint-Etienne","Rhone-Alpes",171961,12897075)) TabClient.append(C.Consommateur(0.7504915784,-0.0698131701,"Toulon","Provence-Alpes-Cote dAzur",165514,12413550)) TabClient.append(C.Consommateur(0.7853981634,0.0698131701,"Grenoble","Rhone-Alpes",155632,11672400)) TabClient.append(C.Consommateur(0.8203047484,0.0174532925,"Dijon","Bourgogne",152110,11408250)) TabClient.append(C.Consommateur(0.8203047484,0.0523598776,"Angers","Pays de la Loire",147305,11047875)) TabClient.append(C.Consommateur(0.7853981634,0,"Villeurbanne","Rhone-Alpes",144751,10856325)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Le Mans","Pays de la Loire",142281,10671075)) TabClient.append(C.Consommateur(0.7504915784,0.1047197551,"Aix-en-Provence","Provence-Alpes-Cote dAzur",141895,10642125)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Brest","Bretagne",141315,10598625)) TabClient.append(C.Consommateur(0.7504915784,0.1047197551,"Nimes","Languedoc-Roussillon",140747,10556025)) TabClient.append(C.Consommateur(0.7853981634,0.0174532925,"Limoges","Limousin",139216,10441200)) TabClient.append(C.Consommateur(0.7853981634,0.034906585,"Clermont-Ferrand","Auvergne",138588,10394100)) TabClient.append(C.Consommateur(0.8203047484,0.1221730476,"Tours","Centre",135218,10141350)) TabClient.append(C.Consommateur(0.8552113335,0.0174532925,"Amiens","Picardie",133998,10049850)) TabClient.append(C.Consommateur(0.8552113335,0,"Metz","Lorraine",121841,9138075)) TabClient.append(C.Consommateur(0.7330382858,0.1047197551,"Perpignan","Languedoc-Roussillon",117905,8842875)) TabClient.append(C.Consommateur(0.8203047484,0.034906585,"Besancon","Franche-Comte",117392,8804400)) TabClient.append(C.Consommateur(0.8203047484,0.034906585,"Orleans","Centre",113224,8491800)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Boulogne-Billancourt","Ile-de-France",113085,8481375)) TabClient.append(C.Consommateur(0.8203047484,0.0523598776,"Mulhouse","Alsace",111156,8336700)) TabClient.append(C.Consommateur(0.8552113335,0.034906585,"Rouen","Haute-Normandie",110688,8301600)) TabClient.append(C.Consommateur(0.8203047484,0.0523598776,"Cean","Basse-Normandie",109312,8198400)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Nancy","Lorraine",106318,7973850)) TabClient.append(C.Consommateur(0.837758041,0.0698131701,"Saint-Denis","Ile-de-France",105749,7931175)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Montreuil","Ile-de-France",103192,7739400)) TabClient.append(C.Consommateur(0.837758041,0,"Argenteuil","Ile-de-France",102844,7713300)) TabClient.append(C.Consommateur(0.872664626,0.034906585,"Roubaix","Nord-Pas-de-Calais",95028,7127100)) TabClient.append(C.Consommateur(0.8901179185,0.034906585,"Dunkerque","Nord-Pas-de-Calais",92923,6969225)) TabClient.append(C.Consommateur(0.872664626,0.034906585,"Tourcoing","Nord-Pas-de-Calais",92389,6929175)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Nanterre","Ile-de-France",89966,6747450)) TabClient.append(C.Consommateur(0.7504915784,0,"Avignion","Provence-Alpes-Cote dAzur",89592,6719400)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Creteil","Ile-de-France",89359,6701925)) TabClient.append(C.Consommateur(0.8028514559,0.034906585,"Poitiers","Poitou-Charentes",88795,6659625)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Courbevoie","Ile-de-France",86945,6520875)) TabClient.append(C.Consommateur(0.837758041,0.1221730476,"Versailles","Ile-de-France",86477,6485775)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Vitry-sur-Seine","Ile-de-France",85380,6403500)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Colombes","Ile-de-France",84572,6342900)) TabClient.append(C.Consommateur(0.7504915784,-0.0174532925,"Pau","Aquitaine",82763,6207225)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Aulnay-sous-Bois","Ile-de-France",82525,6189375)) TabClient.append(C.Consommateur(0.837758041,0.0174532925,"Asnieres-sur -Seine","Ile-de-France",81603,6120225)) TabClient.append(C.Consommateur(0.837758041,0.1221730476,"Rueil-Malmaison","Ile-de-France",79065,5929875)) TabClient.append(C.Consommateur(0.7504915784,0.0523598776,"Antibes","Provence-Alpes-Cote dAzur",75553,5666475)) TabClient.append(C.Consommateur(0.837758041,0.1221730476,"Saint-Maur-des-Fosses","Ile-de-France",75251,5643825)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Champigny-Sur-Marne","Ile-de-France",75090,5631750)) TabClient.append(C.Consommateur(0.8028514559,0.034906585,"La Rochelle","Poitou-Charentes",74707,5603025)) TabClient.append(C.Consommateur(0.837758041,0,"Aubervilliers","Ile-de-France",74701,5602575)) TabClient.append(C.Consommateur(0.872664626,-0.034906585,"Calais","Nord-Pas-de-Calais",74336,5575200)) TabClient.append(C.Consommateur(0.7504915784,0.0698131701,"Cannes","Provence-Alpes-Cote dAzur",73372,5502900)) TabClient.append(C.Consommateur(0.7504915784,0.1396263402,"Beziers","Languedoc-Roussillon",70957,5321775)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Colmar","Alsace",67214,5041050)) TabClient.append(C.Consommateur(0.8203047484,0.0523598776,"Bourges","Centre",66786,5008950)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Drancy","Ile-de-France",66670,5000250)) TabClient.append(C.Consommateur(0.7679448709,0.034906585,"Merignac","Aquitaine",66488,4986600)) TabClient.append(C.Consommateur(0.8203047484,-0.0698131701,"Saint-Nazaire","Pays de la Loire",66348,4976100)) TabClient.append(C.Consommateur(0.7679448709,0.0872664626,"Valence","Rhone-Alpes",64367,4827525)) TabClient.append(C.Consommateur(0.7155849933,0.034906585,"Ajaccio","Corse",64306,4822950)) TabClient.append(C.Consommateur(0.837758041,0.0698131701,"Issy-les-Moulineaux","Ile-de-France",64027,4802025)) TabClient.append(C.Consommateur(0.872664626,0.034906585,"Villeneuve-dAscq","Nord-Pas-de-Calais",63844,4788300)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Levallois-Perret","Ile-de-France",63436,4757700)) TabClient.append(C.Consommateur(0.837758041,0.0698131701,"Noisy-le-Grand","Ile-de-France",63405,4755375)) TabClient.append(C.Consommateur(0.8203047484,0.034906585,"Quimper","Bretagne",63387,4754025)) TabClient.append(C.Consommateur(0.7504915784,-0.0523598776,"La Seyne-sur-Mer","Provence-Alpes-Cote dAzur",61514,4613550)) TabClient.append(C.Consommateur(0.837758041,0,"Antony","Ile-de-France",61393,4604475)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Troyes","Champagne-Ardenne",61188,4589100)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Neuilly-sur-Seine","Ile-de-France",60501,4537575)) TabClient.append(C.Consommateur(0.837758041,0,"Sarcelles","Ile-de-France",59421,4456575)) TabClient.append(C.Consommateur(0.7853981634,0.0872664626,"Venissieux","Rhone-Alpes",58643,4398225)) TabClient.append(C.Consommateur(0.837758041,0.0174532925,"Clichy","Ile-de-France",58200,4365000)) TabClient.append(C.Consommateur(0.8203047484,0.0523598776,"Lorient","Bretagne",57812,4335900)) TabClient.append(C.Consommateur(0.7679448709,0.034906585,"Pessac","Aquitaine",57593,4319475)) TabClient.append(C.Consommateur(0.837758041,0.1047197551,"Ivry-sur-Seine","Ile-de-France",57254,4294050)) TabClient.append(C.Consommateur(0.8552113335,0.034906585,"Cergy","Ile-de-France",57247,4293525)) TabClient.append(C.Consommateur(0.8028514559,0,"Niort","Poitou-Charentes",56878,4265850)) TabClient.append(C.Consommateur(0.7853981634,0.034906585,"Chambery","Rhone-Alpes",56476,4235700)) TabClient.append(C.Consommateur(0.7679448709,0.034906585,"Montauban","Midi-Pyrenees",56126,4209450)) TabClient.append(C.Consommateur(0.8552113335,0.034906585,"Saint-Quentin","Picardie",55971,4197825)) TabClient.append(C.Consommateur(0.837758041,0.1047197551,"Vilejuif","Ile-de-France",55250,4143750)) TabClient.append(C.Consommateur(0.7504915784,-0.034906585,"Hyeres","Provence-Alpes-Cote dAzur",54686,4101450)) TabClient.append(C.Consommateur(0.8552113335,0.034906585,"Beauvais","Picardie",54461,4084575)) TabClient.append(C.Consommateur(0.8203047484,0.034906585,"Cholet","Pays de la Loire",54121,4059075)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Epinay-sur-Seine","Ile-de-France",53577,4018275)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Bondy","Ile-de-France",53448,4008600)) TabClient.append(C.Consommateur(0.837758041,-0.0174532925,"Fontenay-sous-Bois","Ile-de-France",53258,3994350)) TabClient.append(C.Consommateur(0.7504915784,0.1047197551,"Arles","Provence-Alpes-Cote dAzur",52979,3973425)) TabClient.append(C.Consommateur(0.8203047484,0.034906585,"Vannes","Bretagne",52683,3951225)) TabClient.append(C.Consommateur(0.837758041,0.1047197551,"Chelles","Ile-de-France",52636,3947700)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Maisons-Alfort","Ile-de-France",52619,3946425)) TabClient.append(C.Consommateur(0.837758041,0.0523598776,"Clamart","Ile-de-France",52569,3942675)) TabClient.append(C.Consommateur(0.837758041,0.0174532925,"Evry","Ile-de-France",52403,3930225)) TabClient.append(C.Consommateur(0.8028514559,0,"La Roche-sur-Yon","Pays de la Loire",52234,3917550)) TabClient.append(C.Consommateur(0.7504915784,0.034906585,"Frejus","Provence-Alpes-Cote dAzur",52203,3915225)) TabClient.append(C.Consommateur(0.837758041,0.1047197551,"Pantin","Ile-de-France",52161,3912075)) TabClient.append(C.Consommateur(0.7504915784,0.1047197551,"Grasse","Provence-Alpes-Cote dAzur",52019,3901425)) TabClient.append(C.Consommateur(0.837758041,0.034906585,"Sartrouville","Ile-de-France",51459,3859425)) TabClient.append(C.Consommateur(0.7504915784,0,"Narbonne","Languedoc-Roussillon",51227,3842025)) TabClient.append(C.Consommateur(0.8552113335,0,"Evreux","Haute-Normandie",51193,3839475)) TabClient.append(C.Consommateur(0.8203047484,0,"Laval","Pays de la Loire",51182,3838650)) TabClient.append(C.Consommateur(0.837758041,0,"Le Blanc-Mesnil","Ile-de-France",51106,3832950)) TabClient.append(C.Consommateur(0.7853981634,0,"Annecy","Rhone-Alpes",50254,3769050)) TabClient.append(C.Consommateur(0.8203047484,0,"Belfort","Franche-Comte",50199,3764925)) TabClient.append(C.Consommateur(0.837758041,0,"Sevran","Ile-de-France",50021,3751575)) """ Test Unitaire""" """F.distance OK""" print("Distance Critique") print(F.findCriticalDistance(TabProd,TabClient)) """generation des set Personnalises""" T1=F.generateSetSimplified(TabProd,TabClient) print("Sets generes\n") print("vzrification de asClient") for s in T1: for c in s.TabClient: if (s.asClient(c)==0): print("asClient nest pas bien implemente") con=1 index=0 for client in TabClient: index+=1 c=0 for s in T1: if(s.asClient(client)==1): c=1 break if(c==0): con=0 print("IL y a des clients non pourvus") print(client.name) print(client.key) print("Index in TabClient") print(index) break if(con==1): print("Tous les clients ont un producteur attitres") """T2=F.linearRelaxation(T1, TabClient) print("Fin relaxation lineaire") print(T2) T3=F.repairingFinal(T1,F.decisionToPickSet(T2), TabClient) print(T2) T3=F.repairingFinal(T1,F.decisionToPickSet(T2), TabClient) print("Solution de la relaxation lineaire initiale\n") print(T2) print("Choix en fonction des probabilite allouee avec la rel. Lin\n") T4=F.decisionToPickSet(T2) print(T4) print("Choix 'repare', tous les clients sont couverts\n") T5=F.decisionToPickSet(T3) print(T5) acc=0 for i in range(len(T2)): if (T5[i]!=T4[i]): acc+=1 print("Nombre de choix repare:") print(acc) print("Nombre de Set envisages:") print(len(T5)) """ T2=F.greedyAlgorithm(T1,TabClient) print(T2) print(len(T1[0].TabClient)) for i in TabProd: print("je change de prod") for j in TabClient: print(F.distance(i,j))
Python
#!/usr/bin/python3.2 # -*-coding:utf-8 -* import Consommateur import Producteur from FonctionSetCover import * """ il faudra via les modules qui seront mises en place remplir TabProd & TabClient """ TabClient=[] TabProd=[] TabProd.append(Producteur("P1","Rhône-Alpes",45,5,30.9,1122612,0,"NUCLEAR")) TabProd.append(Producteur("P2","Centre",47,1,30.9,979534,0,"NUCLEAR")) TabProd.append(Producteur("P3","Haute-Normandie",49,0,30.9,665863,0,"NUCLEAR")) TabProd.append(Producteur("P4","Champagne-Ardenne",48,4,30.9,5090275,0,"NUCLEAR")) TabProd.append(Producteur("P5","Nord-Pas-de-Calais",50,2,30.9,4925185,0,"NUCLEAR")) TabProd.append(Producteur("P6","Lorraine",48,6,30.9,467755,0,"NUCLEAR")) TabProd.append(Producteur("P7","Île-de-France",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P8","Île-de-France",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P9","Provence-Alpes-Côte-d'Azur",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P10","Midi-Pyrénées",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P11","Champagne-Ardenne",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P12","Haute-Normandie",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P13","Bourgogne",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P14","Pays de la Loire",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P15","La Reunion",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P16","Bretagne",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P17","Languedoc-Roussillon",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P18","Limousin",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P19","Auvergne",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P20","Picardie",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P21","Lorraine",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P22","Franche-Comté",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P23","Alsace",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P24","Basse-Normandie",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P25","Poitou-Charentes",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P26","Martinique",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P27","Aquitaine",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P28","Corse",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P29","Guadeloupe",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P30","Guyane française",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P31","Corse",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P32","Corse",46,2,30.9,126569,0,"NUCLEAR")) TabProd.append(Producteur("P33","Corse",46,2,30.9,126569,0,"NUCLEAR")) TabClient.append(Consommateur(48,2,"Paris","Ile-de-France",22234105,1667557875)) TabClient.append(Consommateur(43,5,"Marseille","Provence-Alpes-Côte d’Azur",850602,63795150)) TabClient.append(Consommateur(45, 4,"Lyon","Rhône-Alpes",479803,35985225)) TabClient.append(Consommateur(43, 1,"Toulouse","Midi-Pyrénées",440204,33015300)) TabClient.append(Consommateur(43, 7,"Nice","Provence-Alpes-Côte d’Azur",340735,25555125)) TabClient.append(Consommateur(47, -1,"Nantes","Pays de la Loire",282047,21153525)) TabClient.append(Consommateur(48, 7,"Strasbourg","Alsace",271708,20378100)) TabClient.append(Consommateur(43, 3,"Montpellier","Languedoc-Roussillon",255080,19131000)) TabClient.append(Consommateur(44, 0,"Bordeaux","Aquitaine",236725,17754375)) TabClient.append(Consommateur(50, 3,"Lille","Nord-Pas-de-Calais",226827,17012025)) TabClient.append(Consommateur(48, 1,"Rennes","Bretagne",206604,15495300)) TabClient.append(Consommateur(49, 4,"Reims","Champagne-Ardenne",180842,13563150)) TabClient.append(Consommateur(49, 0,"Le Havre","Haute-Normandie",177259,13294425)) TabClient.append(Consommateur(45, 4,"Saint-Etienne","Rhône-Alpes",171961,12897075)) TabClient.append(Consommateur(43, 5,"Toulon","Provence-Alpes-Côte d’Azur",165514,12413550)) TabClient.append(Consommateur(45, 5,"Grenoble","Rhône-Alpes",155632,11672400)) TabClient.append(Consommateur(47, 5,"Dijon","Bourgogne",152110,11408250)) TabClient.append(Consommateur(47, 0,"Angers","Pays de la Loire",147305,11047875)) TabClient.append(Consommateur(0,-20.55,"Saint-Denis","La Réunion",145209,10890675)) TabClient.append(Consommateur(45, 4,"Villeurbanne","Rhône-Alpes",144751,10856325)) TabClient.append(Consommateur(48, 0,"Le Mans","Pays de la Loire",142281,10671075)) TabClient.append(Consommateur(43, 5,"Aix-en-Provence","Provence-Alpes-Côte d’Azur",141895,10642125)) TabClient.append(Consommateur(48, -4,"Brest","Bretagne",141315,10598625)) TabClient.append(Consommateur(43, 4,"Nîmes","Languedoc-Roussillon",140747,10556025)) TabClient.append(Consommateur(45, 1,"Limoges","Limousin",139216,10441200)) TabClient.append(Consommateur(45, 3,"Clermont-Ferrand","Auvergne",138588,10394100)) TabClient.append(Consommateur(47, 0,"Tours","Centre",135218,10141350)) TabClient.append(Consommateur(49, 2,"Amiens","Picardie",133998,10049850)) TabClient.append(Consommateur(49, 6,"Metz","Lorraine",121841,9138075)) TabClient.append(Consommateur(42, 2,"Perpignan","Languedoc-Roussillon",117905,8842875)) TabClient.append(Consommateur(47, 6,"Besançon","Franche-Comté",117392,8804400)) TabClient.append(Consommateur(47, 1,"Orléans","Centre",113224,8491800)) TabClient.append(Consommateur(48, 2,"Boulogne-Billancourt","Île-de-France",113085,8481375)) TabClient.append(Consommateur(47, 7,"Mulhouse","Alsace",111156,8336700)) TabClient.append(Consommateur(49, 1,"Rouen","Haute-Normandie",110688,8301600)) TabClient.append(Consommateur(47, 0,"Cean","Basse-Normandie",109312,8198400)) TabClient.append(Consommateur(48, 6,"Nancy","Lorraine",106318,7973850)) TabClient.append(Consommateur(48, 2,"Saint-Denis","Île-de-France",105749,7931175)) TabClient.append(Consommateur(44,-93,"Saint-Paul","La Réunion", 103498,7762350)) TabClient.append(Consommateur(48, 2,"Montreuil","Île-de-France",103192,7739400)) TabClient.append(Consommateur(48, 2,"Argenteuil","Île-de-France",102844,7713300)) TabClient.append(Consommateur(50, 3,"Roubaix","Nord-Pas-de-Calais",95028,7127100)) TabClient.append(Consommateur(51, 2,"Dunkerque","Nord-Pas-de-Calais",92923,6969225)) TabClient.append(Consommateur(50, 3,"Tourcoing","Nord-Pas-de-Calais",92389,6929175)) TabClient.append(Consommateur(48, 2,"Nanterre","Île-de-France",89966,6747450)) TabClient.append(Consommateur(43, 4,"Avignion","Provence-Alpes-Côte d’Azur",89592,6719400)) TabClient.append(Consommateur(48, 2,"Créteil","Île-de-France",89359,6701925)) TabClient.append(Consommateur(46, 0,"Poitiers","Poitou-Charentes",88795,6659625)) TabClient.append(Consommateur(14, 61,"Fort-de-France","Martinique",88440,6633000)) TabClient.append(Consommateur(48, 2,"Courbevoie","Île-de-France",86945,6520875)) TabClient.append(Consommateur(48, 2,"Versailles","Île-de-France",86477,6485775)) TabClient.append(Consommateur(48, 2,"Vitry-sur-Seine","Île-de-France",85380,6403500)) TabClient.append(Consommateur(48, 2,"Colombes","Île-de-France",84572,6342900)) TabClient.append(Consommateur(43, 0,"Pau","Aquitaine",82763,6207225)) TabClient.append(Consommateur(48, 2,"Aulnay-sous-Bois","Île-de-France",82525,6189375)) TabClient.append(Consommateur(48, 2,"Asnières-sur -Seine","Île-de-France",81603,6120225)) TabClient.append(Consommateur(48, 2,"Rueil-Malmaison","Île-de-France",79065,5929875)) TabClient.append(Consommateur(0,-21.55,"Saint-Pierre","La Réunion",77146,5785950)) TabClient.append(Consommateur(43, 7,"Antibes","Provence-Alpes-Côte d’Azur",75553,5666475)) TabClient.append(Consommateur(48, 2,"Saint-Maur-des-Fossés","Île-de-France",75251,5643825)) TabClient.append(Consommateur(48, 2,"Champigny-Sur-Marne","Île-de-France",75090,5631750)) TabClient.append(Consommateur(46, -1,"La Rochelle","Poitou-Charentes",74707,5603025)) TabClient.append(Consommateur(48, 2,"Aubervilliers","Île-de-France",74701,5602575)) TabClient.append(Consommateur(50, 1,"Calais","Nord-Pas-de-Calais",74336,5575200)) TabClient.append(Consommateur(43, 7,"Cannes","Provence-Alpes-Côte d’Azur",73372,5502900)) TabClient.append(Consommateur(0,-21.55,"Le Tampon","La Réunion",72658,5449350)) TabClient.append(Consommateur(43, 3,"Béziers","Languedoc-Roussillon",70957,5321775)) TabClient.append(Consommateur(48, 7,"Colmar","Alsace",67214,5041050)) TabClient.append(Consommateur(47, 2,"Bourges","Centre",66786,5008950)) TabClient.append(Consommateur(48, 2,"Drancy","Île-de-France",66670,5000250)) TabClient.append(Consommateur(44, 0,"Mérignac","Aquitaine",66488,4986600)) TabClient.append(Consommateur(47, -2,"Saint-Nazaire","Pays de la Loire",66348,4976100)) TabClient.append(Consommateur(44, 4,"Valence","Rhône-Alpes",64367,4827525)) TabClient.append(Consommateur(41, 8,"Ajaccio","Corse",64306,4822950)) TabClient.append(Consommateur(48, 2,"Issy-les-Moulineaux","Île-de-France",64027,4802025)) TabClient.append(Consommateur(50, 3,"Villeneuve-d\'Ascq","Nord-Pas-de-Calais",63844,4788300)) TabClient.append(Consommateur(48, 2,"Levallois-Perret","Île-de-France",63436,4757700)) TabClient.append(Consommateur(48, 2,"Noisy-le-Grand","Île-de-France",63405,4755375)) TabClient.append(Consommateur(47, -4,"Quimper","Bretagne",63387,4754025)) TabClient.append(Consommateur(43, 5,"La Seyne-sur-Mer","Provence-Alpes-Côte d’Azur",61514,4613550)) TabClient.append(Consommateur(48, 2,"Antony","Île-de-France",61393,4604475)) TabClient.append(Consommateur(48, 4,"Troyes","Champagne-Ardenne",61188,4589100)) TabClient.append(Consommateur(48, 2,"Neuilly-sur-Seine","Île-de-France",60501,4537575)) TabClient.append(Consommateur(48, 2,"Sarcelles","Île-de-France",59421,4456575)) TabClient.append(Consommateur(16,-61,"Les Abymes","Guadeloupe",58836,4412700)) TabClient.append(Consommateur(45, 4,"Vénissieux","Rhône-Alpes",58643,4398225)) TabClient.append(Consommateur(48, 2,"Clichy","Île-de-France",58200,4365000)) TabClient.append(Consommateur(47, -3,"Lorient","Bretagne",57812,4335900)) TabClient.append(Consommateur(44, 0,"Pessac","Aquitaine",57593,4319475)) TabClient.append(Consommateur(48, 2,"Ivry-sur-Seine","Île-de-France",57254,4294050)) TabClient.append(Consommateur(49, 2,"Cergy","Île-de-France",57247,4293525)) TabClient.append(Consommateur(47, 5,"Cayenne","Guyane française",57047,4278525)) TabClient.append(Consommateur(46, 0,"Niort","Poitou-Charentes",56878,4265850)) TabClient.append(Consommateur(45, 5,"Chambéry","Rhône-Alpes",56476,4235700)) TabClient.append(Consommateur(44, 1,"Montauban","Midi-Pyrénées",56126,4209450)) TabClient.append(Consommateur(49, 3,"Saint-Quentin","Picardie",55971,4197825)) TabClient.append(Consommateur(48, 2,"Vilejuif","Île-de-France",55250,4143750)) TabClient.append(Consommateur(43, 6,"Hyères","Provence-Alpes-Côte d’Azur",54686,4101450)) TabClient.append(Consommateur(49, 2,"Beauvais","Picardie",54461,4084575)) TabClient.append(Consommateur(47, 0,"Cholet","Pays de la Loire",54121,4059075)) TabClient.append(Consommateur(48, 2,"Epinay-sur-Seine","Île-de-France",53577,4018275)) TabClient.append(Consommateur(48, 2,"Bondy","Île-de-France",53448,4008600)) TabClient.append(Consommateur(48, 2,"Fontenay-sous-Bois","Île-de-France",53258,3994350)) TabClient.append(Consommateur(43, 6,"Arles","Provence-Alpes-Côte d’Azur",52979,3973425)) TabClient.append(Consommateur(0,-20.55,"Saint-André","La Réunion",52939,3970425)) TabClient.append(Consommateur(47, -2,"Vannes","Bretagne",52683,3951225)) TabClient.append(Consommateur(48, 2,"Chelles","Île-de-France",52636,3947700)) TabClient.append(Consommateur(48, 2,"Maisons-Alfort","Île-de-France",52619,3946425)) TabClient.append(Consommateur(48, 2,"Clamart","Île-de-France",52569,3942675)) TabClient.append(Consommateur(48, 2,"Evry","Île-de-France",52403,3930225)) TabClient.append(Consommateur(46, -1,"La Roche-sur-Yon","Pays de la Loire",52234,3917550)) TabClient.append(Consommateur(43, 6,"Fréjus","Provence-Alpes-Côte d’Azur",52203,3915225)) TabClient.append(Consommateur(48, 2,"Pantin","Île-de-France",52161,3912075)) TabClient.append(Consommateur(43, 6,"Grasse","Provence-Alpes-Côte d’Azur",52019,3901425)) TabClient.append(Consommateur(38, -90,"Saint-Louis","La Réunion",51460,3859500)) TabClient.append(Consommateur(48, 2,"Sartrouville","Île-de-France",51459,3859425)) TabClient.append(Consommateur(43, 3,"Narbonne","Languedoc-Roussillon",51227,3842025)) TabClient.append(Consommateur(49, 1,"Evreux","Haute-Normandie",51193,3839475)) TabClient.append(Consommateur(47, 0,"Laval","Pays de la Loire",51182,3838650)) TabClient.append(Consommateur(48, 2,"Le Blanc-Mesnil","Île-de-France",51106,3832950)) TabClient.append(Consommateur(45, 6,"Annecy","Rhône-Alpes",50254,3769050)) TabClient.append(Consommateur(47, 6,"Belfort","Franche-Comté",50199,3764925)) TabClient.append(Consommateur(48, 2,"Sevran","Île-de-France",50021,3751575)) def test (TabProd,TabClient): T=[""] T2=[""] T3=[""] T=generateSet(TabProd,TabClient) T2=linearRelaxation(T) T3=repairingFinal(T,decisionToPickSet(T2)) return toPlotEdges(T,T3)
Python
import networkx as nx import matplotlib.pyplot as plt class Map: # constantes latitude_min = 42.19 latitude_max = 51.5 longitude_min = 4.46 longitude_max = 8.14 def Draw (sets, filename): G = nx.Graph () position = {} # Building graphs for selection in sets : G.add_node (selection.producteur.name) positions [selection.producteur.name] = ((selection.producteur.latitude - latitude_min) / (latitude_max - latitude_min), (selection.producteur.longitude - longitude_min) / (longitude_max - longitude_min)) # colors [selection.producteur.name] = color for client in selection.producteur.TabClient : G.add_node (client.name) G.add_edge (selection.producteur.name, client.name) # edge_colors [(selection.producteur.name, client.name)] = color positions [client.name] = ((client.latitude - latitude_min) / (latitude_max - latitude_min), (client.longitude - longitude_min) / (longitude_max - longitude_min)) plt.figure (figsize = (8,8)) nx.draw_networkx_nodes (G, positions, G.nodes ()) for selection in sets : nx.draw_networkx_edges (G, positions,[(selection.producteur.name, n) for n in G.neighbors(selection.producteur.name)], 80, selection.producteur.color) plt.xlim (-0.05, 1.05) plt.ylim (-0.05, 1.05) plt.axis ('off') plt.savefig (filename) plt.show ()
Python
import FonctionSetCover as F import Producteur as P import Set as S import Consommateur as C TabClient=[] TabProd=[] TabProd.append(P.Producteur("P1","Rhone-Alpes",45,5,30.9,1122612,0,10)) TabProd.append(P.Producteur("P2","Centre",47,1,30.9,979534,0,10)) TabProd.append(P.Producteur("P3","Haute-Normandie",49,0,30.9,665863,0,10)) TabProd.append(P.Producteur("P4","Champagne-Ardenne",48,4,30.9,5090275,0,10)) TabProd.append(P.Producteur("P5","Nord-Pas-de-Calais",50,2,30.9,4925185,0,10)) TabProd.append(P.Producteur("P6","Lorraine",48,6,30.9,467755,0,10)) TabProd.append(P.Producteur("P7","Ile-de-France",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P8","Ile-de-France",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P9","Provence-Alpes-Cote-d'Azur",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P10","Midi-Pyrenees",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P11","Champagne-Ardenne",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P12","Haute-Normandie",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P13","Bourgogne",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P14","Pays de la Loire",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P15","La Reunion",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P16","Bretagne",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P17","Languedoc-Roussillon",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P18","Limousin",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P19","Auvergne",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P20","Picardie",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P21","Lorraine",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P22","Franche-Comte",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P23","Alsace",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P24","Basse-Normandie",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P25","Poitou-Charentes",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P26","Martinique",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P27","Aquitaine",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P28","Corse",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P29","Guadeloupe",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P30","Guyane francaise",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P31","Corse",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P32","Corse",46,2,30.9,126569,0,10)) TabProd.append(P.Producteur("P33","Corse",46,2,30.9,126569,0,10)) TabClient.append(C.Consommateur(48,2,"Paris","Ile-de-France",22234105,1667557875)) TabClient.append(C.Consommateur(43,5,"Marseille","Provence-Alpes-Cote d'Azur",850602,63795150)) TabClient.append(C.Consommateur(45, 4,"Lyon","Rhone-Alpes",479803,35985225)) TabClient.append(C.Consommateur(43, 1,"Toulouse","Midi-Pyrenees",440204,33015300)) TabClient.append(C.Consommateur(43, 7,"Nice","Provence-Alpes-Cote d'Azur",340735,25555125)) TabClient.append(C.Consommateur(47, -1,"Nantes","Pays de la Loire",282047,21153525)) TabClient.append(C.Consommateur(48, 7,"Strasbourg","Alsace",271708,20378100)) TabClient.append(C.Consommateur(43, 3,"Montpellier","Languedoc-Roussillon",255080,19131000)) TabClient.append(C.Consommateur(44, 0,"Bordeaux","Aquitaine",236725,17754375)) TabClient.append(C.Consommateur(50, 3,"Lille","Nord-Pas-de-Calais",226827,17012025)) TabClient.append(C.Consommateur(48, 1,"Rennes","Bretagne",206604,15495300)) TabClient.append(C.Consommateur(49, 4,"Reims","Champagne-Ardenne",180842,13563150)) TabClient.append(C.Consommateur(49, 0,"Le Havre","Haute-Normandie",177259,13294425)) TabClient.append(C.Consommateur(45, 4,"Saint-Etienne","Rhone-Alpes",171961,12897075)) TabClient.append(C.Consommateur(43, 5,"Toulon","Provence-Alpes-Cote d'Azur",165514,12413550)) TabClient.append(C.Consommateur(45, 5,"Grenoble","Rhone-Alpes",155632,11672400)) TabClient.append(C.Consommateur(47, 5,"Dijon","Bourgogne",152110,11408250)) TabClient.append(C.Consommateur(47, 0,"Angers","Pays de la Loire",147305,11047875)) TabClient.append(C.Consommateur(0,-20.55,"Saint-Denis","La Reunion",145209,10890675)) TabClient.append(C.Consommateur(45, 4,"Villeurbanne","Rhone-Alpes",144751,10856325)) TabClient.append(C.Consommateur(48, 0,"Le Mans","Pays de la Loire",142281,10671075)) TabClient.append(C.Consommateur(43, 5,"Aix-en-Provence","Provence-Alpes-Cote d'Azur",141895,10642125)) TabClient.append(C.Consommateur(48, -4,"Brest","Bretagne",141315,10598625)) TabClient.append(C.Consommateur(43, 4,"Nimes","Languedoc-Roussillon",140747,10556025)) TabClient.append(C.Consommateur(45, 1,"Limoges","Limousin",139216,10441200)) TabClient.append(C.Consommateur(45, 3,"Clermont-Ferrand","Auvergne",138588,10394100)) TabClient.append(C.Consommateur(47, 0,"Tours","Centre",135218,10141350)) TabClient.append(C.Consommateur(49, 2,"Amiens","Picardie",133998,10049850)) TabClient.append(C.Consommateur(49, 6,"Metz","Lorraine",121841,9138075)) TabClient.append(C.Consommateur(42, 2,"Perpignan","Languedoc-Roussillon",117905,8842875)) TabClient.append(C.Consommateur(47, 6,"Besancon","Franche-Comte",117392,8804400)) TabClient.append(C.Consommateur(47, 1,"Orleans","Centre",113224,8491800)) TabClient.append(C.Consommateur(48, 2,"Boulogne-Billancourt","Ile-de-France",113085,8481375)) TabClient.append(C.Consommateur(47, 7,"Mulhouse","Alsace",111156,8336700)) TabClient.append(C.Consommateur(49, 1,"Rouen","Haute-Normandie",110688,8301600)) TabClient.append(C.Consommateur(47, 0,"Cean","Basse-Normandie",109312,8198400)) TabClient.append(C.Consommateur(48, 6,"Nancy","Lorraine",106318,7973850)) TabClient.append(C.Consommateur(48, 2,"Saint-Denis","Ile-de-France",105749,7931175)) TabClient.append(C.Consommateur(44,-93,"Saint-Paul","La Reunion", 103498,7762350)) TabClient.append(C.Consommateur(48, 2,"Montreuil","Ile-de-France",103192,7739400)) TabClient.append(C.Consommateur(48, 2,"Argenteuil","Ile-de-France",102844,7713300)) TabClient.append(C.Consommateur(50, 3,"Roubaix","Nord-Pas-de-Calais",95028,7127100)) TabClient.append(C.Consommateur(51, 2,"Dunkerque","Nord-Pas-de-Calais",92923,6969225)) TabClient.append(C.Consommateur(50, 3,"Tourcoing","Nord-Pas-de-Calais",92389,6929175)) TabClient.append(C.Consommateur(48, 2,"Nanterre","Ile-de-France",89966,6747450)) TabClient.append(C.Consommateur(43, 4,"Avignion","Provence-Alpes-Cote d'Azur",89592,6719400)) TabClient.append(C.Consommateur(48, 2,"Creteil","Ile-de-France",89359,6701925)) TabClient.append(C.Consommateur(46, 0,"Poitiers","Poitou-Charentes",88795,6659625)) TabClient.append(C.Consommateur(14, 61,"Fort-de-France","Martinique",88440,6633000)) TabClient.append(C.Consommateur(48, 2,"Courbevoie","Ile-de-France",86945,6520875)) TabClient.append(C.Consommateur(48, 2,"Versailles","Ile-de-France",86477,6485775)) TabClient.append(C.Consommateur(48, 2,"Vitry-sur-Seine","Ile-de-France",85380,6403500)) TabClient.append(C.Consommateur(48, 2,"Colombes","Ile-de-France",84572,6342900)) TabClient.append(C.Consommateur(43, 0,"Pau","Aquitaine",82763,6207225)) TabClient.append(C.Consommateur(48, 2,"Aulnay-sous-Bois","Ile-de-France",82525,6189375)) TabClient.append(C.Consommateur(48, 2,"Asnieres-sur -Seine","Ile-de-France",81603,6120225)) TabClient.append(C.Consommateur(48, 2,"Rueil-Malmaison","Ile-de-France",79065,5929875)) TabClient.append(C.Consommateur(0,-21.55,"Saint-Pierre","La Reunion",77146,5785950)) TabClient.append(C.Consommateur(43, 7,"Antibes","Provence-Alpes-Cote d'Azur",75553,5666475)) TabClient.append(C.Consommateur(48, 2,"Saint-Maur-des-Fosses","Ile-de-France",75251,5643825)) TabClient.append(C.Consommateur(48, 2,"Champigny-Sur-Marne","Ile-de-France",75090,5631750)) TabClient.append(C.Consommateur(46, -1,"La Rochelle","Poitou-Charentes",74707,5603025)) TabClient.append(C.Consommateur(48, 2,"Aubervilliers","Ile-de-France",74701,5602575)) TabClient.append(C.Consommateur(50, 1,"Calais","Nord-Pas-de-Calais",74336,5575200)) TabClient.append(C.Consommateur(43, 7,"Cannes","Provence-Alpes-Cote d'Azur",73372,5502900)) TabClient.append(C.Consommateur(0,-21.55,"Le Tampon","La Reunion",72658,5449350)) TabClient.append(C.Consommateur(43, 3,"Beziers","Languedoc-Roussillon",70957,5321775)) TabClient.append(C.Consommateur(48, 7,"Colmar","Alsace",67214,5041050)) TabClient.append(C.Consommateur(47, 2,"Bourges","Centre",66786,5008950)) TabClient.append(C.Consommateur(48, 2,"Drancy","Ile-de-France",66670,5000250)) TabClient.append(C.Consommateur(44, 0,"Merignac","Aquitaine",66488,4986600)) TabClient.append(C.Consommateur(47, -2,"Saint-Nazaire","Pays de la Loire",66348,4976100)) TabClient.append(C.Consommateur(44, 4,"Valence","Rhone-Alpes",64367,4827525)) TabClient.append(C.Consommateur(41, 8,"Ajaccio","Corse",64306,4822950)) TabClient.append(C.Consommateur(48, 2,"Issy-les-Moulineaux","Ile-de-France",64027,4802025)) TabClient.append(C.Consommateur(50, 3,"Villeneuve-d\'Ascq","Nord-Pas-de-Calais",63844,4788300)) TabClient.append(C.Consommateur(48, 2,"Levallois-Perret","Ile-de-France",63436,4757700)) TabClient.append(C.Consommateur(48, 2,"Noisy-le-Grand","Ile-de-France",63405,4755375)) TabClient.append(C.Consommateur(47, -4,"Quimper","Bretagne",63387,4754025)) TabClient.append(C.Consommateur(43, 5,"La Seyne-sur-Mer","Provence-Alpes-Cote d'Azur",61514,4613550)) TabClient.append(C.Consommateur(48, 2,"Antony","Ile-de-France",61393,4604475)) TabClient.append(C.Consommateur(48, 4,"Troyes","Champagne-Ardenne",61188,4589100)) TabClient.append(C.Consommateur(48, 2,"Neuilly-sur-Seine","Ile-de-France",60501,4537575)) TabClient.append(C.Consommateur(48, 2,"Sarcelles","Ile-de-France",59421,4456575)) TabClient.append(C.Consommateur(16,-61,"Les Abymes","Guadeloupe",58836,4412700)) TabClient.append(C.Consommateur(45, 4,"Venissieux","Rhone-Alpes",58643,4398225)) TabClient.append(C.Consommateur(48, 2,"Clichy","Ile-de-France",58200,4365000)) TabClient.append(C.Consommateur(47, -3,"Lorient","Bretagne",57812,4335900)) TabClient.append(C.Consommateur(44, 0,"Pessac","Aquitaine",57593,4319475)) TabClient.append(C.Consommateur(48, 2,"Ivry-sur-Seine","Ile-de-France",57254,4294050)) TabClient.append(C.Consommateur(49, 2,"Cergy","Ile-de-France",57247,4293525)) TabClient.append(C.Consommateur(47, 5,"Cayenne","Guyane francaise",57047,4278525)) TabClient.append(C.Consommateur(46, 0,"Niort","Poitou-Charentes",56878,4265850)) TabClient.append(C.Consommateur(45, 5,"Chambery","Rhone-Alpes",56476,4235700)) TabClient.append(C.Consommateur(44, 1,"Montauban","Midi-Pyrenees",56126,4209450)) TabClient.append(C.Consommateur(49, 3,"Saint-Quentin","Picardie",55971,4197825)) TabClient.append(C.Consommateur(48, 2,"Vilejuif","Ile-de-France",55250,4143750)) TabClient.append(C.Consommateur(43, 6,"Hyeres","Provence-Alpes-Cote d'Azur",54686,4101450)) TabClient.append(C.Consommateur(49, 2,"Beauvais","Picardie",54461,4084575)) TabClient.append(C.Consommateur(47, 0,"Cholet","Pays de la Loire",54121,4059075)) TabClient.append(C.Consommateur(48, 2,"Epinay-sur-Seine","Ile-de-France",53577,4018275)) TabClient.append(C.Consommateur(48, 2,"Bondy","Ile-de-France",53448,4008600)) TabClient.append(C.Consommateur(48, 2,"Fontenay-sous-Bois","Ile-de-France",53258,3994350)) TabClient.append(C.Consommateur(43, 6,"Arles","Provence-Alpes-Cote d'Azur",52979,3973425)) TabClient.append(C.Consommateur(0,-20.55,"Saint-Andre","La Reunion",52939,3970425)) TabClient.append(C.Consommateur(47, -2,"Vannes","Bretagne",52683,3951225)) TabClient.append(C.Consommateur(48, 2,"Chelles","Ile-de-France",52636,3947700)) TabClient.append(C.Consommateur(48, 2,"Maisons-Alfort","Ile-de-France",52619,3946425)) TabClient.append(C.Consommateur(48, 2,"Clamart","Ile-de-France",52569,3942675)) TabClient.append(C.Consommateur(48, 2,"Evry","Ile-de-France",52403,3930225)) TabClient.append(C.Consommateur(46, -1,"La Roche-sur-Yon","Pays de la Loire",52234,3917550)) TabClient.append(C.Consommateur(43, 6,"Frejus","Provence-Alpes-Cote d'Azur",52203,3915225)) TabClient.append(C.Consommateur(48, 2,"Pantin","Ile-de-France",52161,3912075)) TabClient.append(C.Consommateur(43, 6,"Grasse","Provence-Alpes-Cote d'Azur",52019,3901425)) TabClient.append(C.Consommateur(38, -90,"Saint-Louis","La Reunion",51460,3859500)) TabClient.append(C.Consommateur(48, 2,"Sartrouville","Ile-de-France",51459,3859425)) TabClient.append(C.Consommateur(43, 3,"Narbonne","Languedoc-Roussillon",51227,3842025)) TabClient.append(C.Consommateur(49, 1,"Evreux","Haute-Normandie",51193,3839475)) TabClient.append(C.Consommateur(47, 0,"Laval","Pays de la Loire",51182,3838650)) TabClient.append(C.Consommateur(48, 2,"Le Blanc-Mesnil","Ile-de-France",51106,3832950)) TabClient.append(C.Consommateur(45, 6,"Annecy","Rhone-Alpes",50254,3769050)) TabClient.append(C.Consommateur(47, 6,"Belfort","Franche-Comte",50199,3764925)) TabClient.append(C.Consommateur(48, 2,"Sevran","Ile-de-France",50021,3751575)) """ Test Unitaire""" F.distance(TabClient[0],TabClient[1]) """F.distance OK""" F.findCriticalClient(TabProd[0],TabClient) """generation des set Personnalises""" T1=F.generateSetPerso(TabProd,TabClient) print("Sets generes\n") T2=F.linearRelaxation(T1, TabClient) print("Fin relaxation lineaire") T3=F.repairingFinal(T1,F.decisionToPickSet(T2), TabClient) print(T2) T3=F.repairingFinal(T1,F.decisionToPickSet(T2), TabClient) print("Solution de la relaxation lineaire initiale\n") print(T2) print("Choix en fonction des probabilite allouee avec la rel. Lin\n") T4=F.decisionToPickSet(T2) print(T4) print("Choix 'repare', tous les clients sont couverts\n") T5=F.decisionToPickSet(T3) print(T5) acc=0 for i in range(len(T2)): if (T5[i]!=T4[i]): acc+=1 print("Nombre de choix repare:") print(acc) print("Nombre de Set envisages:") print(len(T5)) for i in T3: if (T3[i]==1): print(T1[i].producteur.name) for j in range(len(T1[i].TabClient)): print(T1[i].TabClient[j].name) print(T1[i].TabClient[j].region)
Python
class Producteur: """ Cette classe contient toutes les informations de la strucuture producteur - name - region - latitude - longitude - cmwh // cost to product 1Mw/h - pmax //Puissance nominale max en Mw/h - pmin //Puissance nomilane min en Mw/h - typeof //Type de production (NUCLEAR, HYDROLIQUE, BIOGAZ, etc..) """ key=-1 def __init__(self, name, region, latitude, longitude, cmwh, pmax, pmin, coutlancement): Producteur.key +=1 self.key=Producteur.key self.name=name self._region=region self._latitude=latitude self._longitude=longitude self._cmwh=cmwh self._pmax=pmax self._pmin=pmin self._coutlancement=coutlancement """ACCESSEURS""" def _get_region(self): return self._region def _get_latitude(self): return self._latitude def _get_longitude(self): return self._longitude def _get_cmwh(self): return self._cmwh def _get_pmax(self): return self._pmax def _get_pmin(self): return self._pmin def _get_coutlancement(self): return self._coutlancement """MODIFICATEUR""" def _set_region(self,region): self._region=region def _set_latitude(self,latitude): self._latitude=latitude def _set_longitude(self,longitude): self._longitude=longitude def _set_cmwh(self,cmwh): self._cmwh=cmwh def _set_pmax(self,pmax): self._pmax=pmax def _set_pmin(self,pmin): self._pmin=pmin def _set_coutlancement(self,coutlancement): self._coutlancement=coutlancement region=property(_get_region,_set_region) latitude=property(_get_latitude,_set_latitude) longitude=property(_get_longitude,_set_longitude) cmwh=property(_get_cmwh,_set_cmwh) pmax=property(_get_pmax,_set_pmax) pmin=property(_get_pmin,_set_pmin) coutlancement=property(_get_coutlancement,_set_cmwh)
Python
class Consommateur: """ Cette classe contient toutes les informations de la strucuture consommateur - name - region - latitude - longitude - population - needs // nbr de MegaWatt/h minimal necessaire """ key=-1 def __init__(self,latitude,longitude,name, region, population, needs): Consommateur.key +=1 self.key=Consommateur.key self.name=name self.region=region self.latitude=latitude self.longitude=longitude self.population=population self.needs=needs
Python
from __future__ import nested_scopes import Consommateur as C import Producteur as P import Set as S from math import * import numpy as np import scipy.optimize as s import random as r """Resultat en metre Distance(Producteur p, Consommateur c""" d=[[56.0921545309,412.902036059,297.5333736374,285.2234197985,229.0978201421,268.7955740074,247.0905749746,395.9514441317,44.7437460488,338.2824193583,395.5008744783,463.1932582293,338.2923921014,66.4697945551,267.8320107274,253.6805294308,316.1612918266,108.2976948333,423.7962776839], [549.0356987475,255.2266783435,525.7766913891,859.6659156619,468.4109650187,871.8262544252,387.1309149898,424.6423265084,565.2851620552,802.8818670808,741.0362188334,141.8487222428,903.4337380964,669.2337347976,762.230196629,780.1504197038,465.7267975823,540.0467590442,407.9058353089], [279.2117628076,285.9500478678,201.7887494971,548.4053290248,327.8887849088,584.1531517395,242.3835152552,144.3495426377,309.548879482,475.6365748661,623.8295909053,196.820953135,669.4757649611,390.8542809918,566.8603113559,567.8201004865,145.7012377876,320.7255034278,151.0347151825], [522.1337467968,281.9323238448,464.6717026802,819.2555660973,472.5514630258,842.5536343254,384.4269269802,354.071770886,543.0738335699,747.7570469553,759.6158117891,124.6629808692,893.0589039939,641.6787745336,761.2386630285,774.718586209,403.4459007338,527.3225250375,334.7249041898], [509.6101307836,446.1767551201,331.7855285207,733.779404429,555.8119152125,793.2320175383,465.2928271937,194.4613751298,542.4558193411,612.7679446253,855.1749396747,282.6254841643,900.1768500184,612.8161606092,803.2786220915,803.1100980134,276.8748687455,557.2895865736,163.3516205646], [222.6805445533,200.8151058884,426.3483074066,535.0024197169,26.8171524372,494.6969750158,80.0218854537,452.0982350485,207.848632883,576.0980635994,313.8403872774,327.9726023246,470.0865570307,310.4827889028,318.833657707,341.3781656667,405.9378769806,145.4766865288,467.340684758], [102.0386766528,467.5812394001,260.3935903961,227.4403427683,299.7261614224,241.5329796069,305.6523294241,376.6484081598,113.7770443634,263.7972115728,462.7391738938,496.0788777349,358.8416068212,66.1936865132,320.0665870145,297.7474520001,292.1206397779,181.0675778035,406.7109392535], [529.0625057361,514.2315757676,316.325429686,719.5854505083,601.7454559336,790.967438768,514.1799956362,185.5155177495,564.295408831,581.857014395,897.935001437,356.8443509396,915.1304763443,622.5218265055,831.0255993911,826.6125096226,270.925822293,588.0612079767,155.3682156712], [424.4343260012,466.6323460605,205.450466974,609.3085444192,517.544323797,679.6681789322,435.2290060165,75.6038561629,460.6481959697,477.9772533319,807.5119627529,332.0491630846,806.9242607541,513.3527810602,729.1935152567,722.3685205954,160.0743390566,490.0104757992,48.5902984164], [319.2435923482,676.2004757502,464.2796270561,111.3705136795,471.4583837638,17.9798369993,509.5801229124,594.9565055601,308.4047616669,296.979125931,496.2009871092,726.4707255706,231.0638469265,199.8102362606,313.8143689637,270.4274090593,509.3322914637,355.0500865644,626.2173073847], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728], [186.8168581986,544.8075453857,365.6427777963,169.4805803313,346.8690513428,136.0576758663,378.3120865176,486.8499413739,176.1431687141,287.6086779664,430.0350798423,594.6851220901,258.4528825808,67.0797197431,261.1425294294,227.4077080309,401.7693469217,227.0683941403,517.2129493759], [268.8985716026,420.2611575523,531.9174933887,456.3792450784,200.1916851086,368.247282995,288.7377950364,604.1175401502,231.7051320711,569.0711575642,147.840487193,547.7093040642,268.4236311164,263.2179126415,103.3685155017,138.5081452614,535.9683980951,186.0236419889,626.8571833509], [324.2843221192,442.4949040531,95.6121164626,499.4924379915,445.3801551732,568.3765563519,373.1338171396,42.4214352075,361.5812066858,378.3429778138,722.9091217272,343.419376908,699.6893859204,405.351724028,630.5604798964,620.5748708715,51.2882406694,398.9677078437,73.2557422084], [734.2499071431,367.9553098186,802.796461078,1062.1160422432,571.8837414295,1037.8082233955,532.1166823285,727.1610986467,734.7640299951,1052.3623974811,745.3102095528,410.5360127503,1002.5552416697,844.0750969465,839.1611341429,871.3550324739,748.5689017813,684.0951103545,716.2538288695], [292.6422457015,364.1781683998,137.2068805724,519.052801301,383.3925755657,571.4159721464,304.8873377727,71.3138232795,327.7030050382,422.8681162961,670.9721989889,268.4236385947,680.7034202223,390.8047301311,594.823866027,590.0218366922,76.0290574672,353.7306539202,88.4665225414], [150.8057373853,231.7378151409,354.0582385644,472.3103818737,65.9471881014,445.0009483008,66.7769002579,391.3331936301,142.3734007226,502.2748156105,352.7713480468,321.3928870707,451.2684170287,250.5263239196,316.6212821663,329.6651153754,338.1068723437,92.2635346764,409.5330078009], [57.4474618125,340.8036728834,218.6617434725,360.1553268265,214.5996207876,370.3133258983,188.4369641419,294.4217253318,92.1484210512,356.2857371508,457.4309431029,362.1699104955,448.2306891103,170.5413585645,360.7699863796,354.3942539882,221.2125167261,131.6268688169,320.2487826787], [354.9148534124,56.2771011454,423.8016612392,680.5454988278,245.9604307269,672.9661814328,169.0279444122,377.9512647614,363.0717256688,662.431006858,523.693695328,119.4901089526,684.8565375156,471.8011149687,540.1464399033,559.4840894681,375.9414760633,326.8721031915,378.0031326213], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [558.8953614054,585.2596684973,320.4305648824,713.4362996923,653.8893743162,796.0510671335,569.8629952304,209.5507316436,595.6449871838,560.1674726838,944.9843801253,433.3547956776,935.9747444693,641.5225623928,864.6683983831,856.3101051855,287.8651143034,627.1027199756,185.8788120619], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [558.8953614054,585.2596684973,320.4305648824,713.4362996923,653.8893743162,796.0510671335,569.8629952304,209.5507316436,595.6449871838,560.1674726838,944.9843801253,433.3547956776,935.9747444693,641.5225623928,864.6683983831,856.3101051855,287.8651143034,627.1027199756,185.8788120619], [313.2464634692,130.5111583941,348.0172081329,630.5708166707,253.4974665624,635.943231199,162.955001241,299.5375724343,328.6904226133,596.8578427491,548.8003335644,99.2453484039,671.5904290594,433.2480498656,538.7944110589,552.1472181197,298.3451734713,306.1439483109,300.5771071508], [286.567124362,207.9293267357,273.5273417456,586.0762141866,282.7247770939,605.974865376,191.3494979486,221.4736558727,309.8976687485,534.2040138642,582.6548438185,134.1774222146,666.400596426,405.4950178951,547.8662608721,554.9766934991,221.2993720345,303.9690862293,224.3203612627], [318.4440537597,619.3800975925,184.4086699699,273.6912115691,516.8199571992,381.4049688071,487.0826959553,313.1366654944,348.2140122643,109.635917344,714.2549403548,576.6192953267,568.4975288017,310.0617455446,566.3277095456,538.4168079085,245.982888225,413.9463724602,342.3950117709], [215.5939050134,435.308612349,478.1668797945,384.1256435627,208.7320895948,301.1692230252,285.4794707829,561.8037979126,177.8414229368,497.2553835886,216.3647285959,543.9412695632,235.3352030942,192.172793474,96.6082810473,107.8262568724,488.5568761053,149.7810905156,586.6453523356], [268.8985716026,420.2611575523,531.9174933887,456.3792450784,200.1916851086,368.247282995,288.7377950364,604.1175401502,231.7051320711,569.0711575642,147.840487193,547.7093040642,268.4236311164,263.2179126415,103.3685155017,138.5081452614,535.9683980951,186.0236419889,626.8571833509], [661.3964615515,644.3943726502,430.5279765294,824.7250588333,740.0417444534,906.8065412979,652.2731994362,312.3307222738,697.4298613818,669.511878569,1036.0519991163,480.2337724197,1042.98482486,748.8237214555,965.5356132345,959.3500217074,394.4394725447,724.240950882,285.1012668744], [85.5144472218,281.028874371,284.0801773466,413.4032371687,139.5031700376,402.6902227099,119.0014246959,337.4957710662,93.2718681256,428.9052698413,401.7032162209,333.4078594725,443.7934091548,200.8078375568,331.2847773569,334.2125152467,275.1315149865,85.0482899409,359.3038589096], [85.5144472218,281.028874371,284.0801773466,413.4032371687,139.5031700376,402.6902227099,119.0014246959,337.4957710662,93.2718681256,428.9052698413,401.7032162209,333.4078594725,443.7934091548,200.8078375568,331.2847773569,334.2125152467,275.1315149865,85.0482899409,359.3038589096], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [57.4474618125,340.8036728834,218.6617434725,360.1553268265,214.5996207876,370.3133258983,188.4369641419,294.4217253318,92.1484210512,356.2857371508,457.4309431029,362.1699104955,448.2306891103,170.5413585645,360.7699863796,354.3942539882,221.2125167261,131.6268688169,320.2487826787], [177.8664571875,462.4073716676,430.8920854961,312.0535375131,241.0575221148,237.0985027488,301.387850819,527.1170428969,143.1662580581,426.0776586782,286.9076546108,550.8595620823,221.2474663375,123.8808075681,135.9005856827,120.5381309228,448.9083511842,145.6146134845,554.0546668724], [57.4474618125,340.8036728834,218.6617434725,360.1553268265,214.5996207876,370.3133258983,188.4369641419,294.4217253318,92.1484210512,356.2857371508,457.4309431029,362.1699104955,448.2306891103,170.5413585645,360.7699863796,354.3942539882,221.2125167261,131.6268688169,320.2487826787], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [102.0386766528,467.5812394001,260.3935903961,227.4403427683,299.7261614224,241.5329796069,305.6523294241,376.6484081598,113.7770443634,263.7972115728,462.7391738938,496.0788777349,358.8416068212,66.1936865132,320.0665870145,297.7474520001,292.1206397779,181.0675778035,406.7109392535], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728], [284.557132086,564.2738795933,524.6970397194,312.6689419024,338.5298138407,201.0155631008,407.852613727,630.0697674075,252.1314000587,466.3229968389,282.7422497584,660.8797698022,110.1135694008,200.0742296021,100.0067749185,55.8557957958,549.1729283817,255.6642658858,658.0857371049], [393.8171957834,669.1521551478,624.2727596916,350.5865167031,442.5788938823,222.2035668515,516.3666493709,735.4573146673,362.5291341977,527.3720260904,319.9035813061,771.2716362004,9.1273800901,299.1558332556,162.2206624192,128.4267873632,653.021773824,366.4811283055,764.1671881962], [284.557132086,564.2738795933,524.6970397194,312.6689419024,338.5298138407,201.0155631008,407.852613727,630.0697674075,252.1314000587,466.3229968389,282.7422497584,660.8797698022,110.1135694008,200.0742296021,100.0067749185,55.8557957958,549.1729283817,255.6642658858,658.0857371049], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [549.0356987475,255.2266783435,525.7766913891,859.6659156619,468.4109650187,871.8262544252,387.1309149898,424.6423265084,565.2851620552,802.8818670808,741.0362188334,141.8487222428,903.4337380964,669.2337347976,762.230196629,780.1504197038,465.7267975823,540.0467590442,407.9058353089], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [179.792240663,220.7222786792,255.6836185744,494.7843023001,193.1508407434,502.2894374985,114.0050921766,262.8496997404,199.9409182871,471.4787960276,487.8955941431,228.4538478884,555.0939519029,299.9739372319,438.8195783018,444.3613372068,223.4909449584,193.4513085965,278.0687541743], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [315.2796606446,658.0133779748,273.8209929052,166.1084069692,519.0075539399,283.6007036624,508.927900067,409.8007212397,335.607940204,41.0980121329,672.0066805818,641.9799589121,484.1179870011,264.9531842659,508.5904638328,474.8786968137,333.6384069539,403.5391823211,440.4611218708], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [585.239841541,252.1097085376,591.2443927795,904.7945286178,477.3234254631,906.586494587,405.5281039099,498.1453340837,596.9572154384,861.5145951218,730.0954801956,194.2023275932,919.9314229201,704.2829483396,770.859216728,792.9494445184,532.670098175,563.4162470582,483.3932174646], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [149.069224813,330.4659773849,405.7336202326,415.857621564,107.5525917099,363.2905054212,174.8914587817,471.1684703815,116.4401301569,487.2408756833,270.6346720159,432.6556081728,342.2304358264,193.5419528876,205.910866661,218.5427544477,405.115908382,55.5139249773,493.5098106849], [315.2796606446,658.0133779748,273.8209929052,166.1084069692,519.0075539399,283.6007036624,508.927900067,409.8007212397,335.607940204,41.0980121329,672.0066805818,641.9799589121,484.1179870011,264.9531842659,508.5904638328,474.8786968137,333.6384069539,403.5391823211,440.4611218708], [501.7501237512,382.6974059107,364.3265419182,755.5627369076,517.7521983539,802.7822596892,425.5585889898,232.6127032154,531.3037848057,651.5848173165,817.3849822807,213.122201087,891.4128597898,612.8488747739,782.0599187326,786.3624644479,304.3723317132,536.2185813913,205.3873690854], [315.2796606446,658.0133779748,273.8209929052,166.1084069692,519.0075539399,283.6007036624,508.927900067,409.8007212397,335.607940204,41.0980121329,672.0066805818,641.9799589121,484.1179870011,264.9531842659,508.5904638328,474.8786968137,333.6384069539,403.5391823211,440.4611218708], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [179.792240663,220.7222786792,255.6836185744,494.7843023001,193.1508407434,502.2894374985,114.0050921766,262.8496997404,199.9409182871,471.4787960276,487.8955941431,228.4538478884,555.0939519029,299.9739372319,438.8195783018,444.3613372068,223.4909449584,193.4513085965,278.0687541743], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728], [451.3420987242,538.8755484617,714.3582619251,596.9939849042,350.0934703113,486.5693942228,442.315556395,782.9835032201,414.0547041627,734.0599508522,53.0569888582,689.7838623421,312.2219205711,433.4954772639,189.3329107735,230.7152262053,717.1881662825,366.7427012332,804.4655094266], [509.6101307836,446.1767551201,331.7855285207,733.779404429,555.8119152125,793.2320175383,465.2928271937,194.4613751298,542.4558193411,612.7679446253,855.1749396747,282.6254841643,900.1768500184,612.8161606092,803.2786220915,803.1100980134,276.8748687455,557.2895865736,163.3516205646], [643.4381432838,732.7163705967,381.8399202998,725.8255518346,771.6124122046,827.521548941,694.8872464437,318.7149829842,681.2296161516,548.390413637,1049.5664832847,589.6352296158,993.7353458913,704.0268392308,947.0012307178,931.7829484285,374.1164464554,724.3637618689,306.9766348861], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [57.4474618125,340.8036728834,218.6617434725,360.1553268265,214.5996207876,370.3133258983,188.4369641419,294.4217253318,92.1484210512,356.2857371508,457.4309431029,362.1699104955,448.2306891103,170.5413585645,360.7699863796,354.3942539882,221.2125167261,131.6268688169,320.2487826787], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [395.8523982032,250.0521356186,330.1981640722,683.3181447426,383.8480034505,711.963469254,291.5711689374,231.9164594844,420.5713067789,610.9048444559,682.4215169647,92.7257320508,777.7107228401,513.4679399452,657.6732122593,665.8261046474,269.7646740818,414.9151736022,219.2976123815], [520.5701466229,325.3137193608,724.4487175949,805.1977148885,317.8139187987,734.617060779,361.4024387783,727.5553584093,498.4214642858,873.4527301055,323.1234664006,495.9995312615,629.8587447633,585.4641783314,465.0913706034,506.6684858684,696.4035237471,430.5958964337,736.0032007151], [424.4343260012,466.6323460605,205.450466974,609.3085444192,517.544323797,679.6681789322,435.2290060165,75.6038561629,460.6481959697,477.9772533319,807.5119627529,332.0491630846,806.9242607541,513.3527810602,729.1935152567,722.3685205954,160.0743390566,490.0104757992,48.5902984164], [727.4145666934,518.7017935143,600.2456092646,992.8875636894,705.8589500445,1036.631421931,615.5493185966,465.4390504242,753.7320388884,886.1103497956,996.4656094103,359.2685173366,1111.651533892,842.6186925658,989.1181172379,998.9990191293,541.1264124369,748.4172521668,435.9511942364], [102.0386766528,467.5812394001,260.3935903961,227.4403427683,299.7261614224,241.5329796069,305.6523294241,376.6484081598,113.7770443634,263.7972115728,462.7391738938,496.0788777349,358.8416068212,66.1936865132,320.0665870145,297.7474520001,292.1206397779,181.0675778035,406.7109392535], [284.557132086,564.2738795933,524.6970397194,312.6689419024,338.5298138407,201.0155631008,407.852613727,630.0697674075,252.1314000587,466.3229968389,282.7422497584,660.8797698022,110.1135694008,200.0742296021,100.0067749185,55.8557957958,549.1729283817,255.6642658858,658.0857371049], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [102.0386766528,467.5812394001,260.3935903961,227.4403427683,299.7261614224,241.5329796069,305.6523294241,376.6484081598,113.7770443634,263.7972115728,462.7391738938,496.0788777349,358.8416068212,66.1936865132,320.0665870145,297.7474520001,292.1206397779,181.0675778035,406.7109392535], [85.5144472218,281.028874371,284.0801773466,413.4032371687,139.5031700376,402.6902227099,119.0014246959,337.4957710662,93.2718681256,428.9052698413,401.7032162209,333.4078594725,443.7934091548,200.8078375568,331.2847773569,334.2125152467,275.1315149865,85.0482899409,359.3038589096], [679.2320657096,314.1450725178,730.4821992378,1006.5789619534,530.7191958504,990.1486438223,480.7254792575,649.9097088587,683.0313908669,986.7366038498,732.2676963469,334.5583578821,969.9194882191,792.6659750115,809.8315534866,839.0991238884,674.8904960249,636.8771428491,637.9638198798], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728], [324.2843221192,442.4949040531,95.6121164626,499.4924379915,445.3801551732,568.3765563519,373.1338171396,42.4214352075,361.5812066858,378.3429778138,722.9091217272,343.419376908,699.6893859204,405.351724028,630.5604798964,620.5748708715,51.2882406694,398.9677078437,73.2557422084], [149.069224813,330.4659773849,405.7336202326,415.857621564,107.5525917099,363.2905054212,174.8914587817,471.1684703815,116.4401301569,487.2408756833,270.6346720159,432.6556081728,342.2304358264,193.5419528876,205.910866661,218.5427544477,405.115908382,55.5139249773,493.5098106849], [57.4474618125,340.8036728834,218.6617434725,360.1553268265,214.5996207876,370.3133258983,188.4369641419,294.4217253318,92.1484210512,356.2857371508,457.4309431029,362.1699104955,448.2306891103,170.5413585645,360.7699863796,354.3942539882,221.2125167261,131.6268688169,320.2487826787], [395.8523982032,250.0521356186,330.1981640722,683.3181447426,383.8480034505,711.963469254,291.5711689374,231.9164594844,420.5713067789,610.9048444559,682.4215169647,92.7257320508,777.7107228401,513.4679399452,657.6732122593,665.8261046474,269.7646740818,414.9151736022,219.2976123815], [241.9573881545,591.5146374191,247.0428811074,157.6280413481,445.2935109156,249.8553281155,438.6438299364,383.9843889657,261.2760940082,114.9402284044,601.4368780507,587.2795003942,434.4385197215,193.06830737,442.6238343356,411.3861006297,301.6840049865,329.1649155322,415.4704772204], [177.8664571875,462.4073716676,430.8920854961,312.0535375131,241.0575221148,237.0985027488,301.387850819,527.1170428969,143.1662580581,426.0776586782,286.9076546108,550.8595620823,221.2474663375,123.8808075681,135.9005856827,120.5381309228,448.9083511842,145.6146134845,554.0546668724], [274.5694298452,96.7226289451,410.2628080534,601.925053624,134.9665920098,580.0210174769,71.3817522608,401.550168412,274.0853649319,610.7307605977,417.1155703321,220.2964881385,576.7281021613,383.5528978686,429.3190667487,449.8773651853,375.0745230825,227.18718079,410.2061992824], [286.567124362,207.9293267357,273.5273417456,586.0762141866,282.7247770939,605.974865376,191.3494979486,221.4736558727,309.8976687485,534.2040138642,582.6548438185,134.1774222146,666.400596426,405.4950178951,547.8662608721,554.9766934991,221.2993720345,303.9690862293,224.3203612627], [395.8523982032,250.0521356186,330.1981640722,683.3181447426,383.8480034505,711.963469254,291.5711689374,231.9164594844,420.5713067789,610.9048444559,682.4215169647,92.7257320508,777.7107228401,513.4679399452,657.6732122593,665.8261046474,269.7646740818,414.9151736022,219.2976123815], [177.8664571875,462.4073716676,430.8920854961,312.0535375131,241.0575221148,237.0985027488,301.387850819,527.1170428969,143.1662580581,426.0776586782,286.9076546108,550.8595620823,221.2474663375,123.8808075681,135.9005856827,120.5381309228,448.9083511842,145.6146134845,554.0546668724], [241.9573881545,591.5146374191,247.0428811074,157.6280413481,445.2935109156,249.8553281155,438.6438299364,383.9843889657,261.2760940082,114.9402284044,601.4368780507,587.2795003942,434.4385197215,193.06830737,442.6238343356,411.3861006297,301.6840049865,329.1649155322,415.4704772204], [629.1373018007,273.3898539275,659.7690899248,953.9653653047,498.5880623289,946.2244993366,437.6413523935,573.4456304994,636.6751926755,922.9787170443,727.1402535081,261.3785863666,942.2277799389,745.7654706181,786.8731520351,812.7656993973,602.7160345806,596.1771182965,560.2467815279], [177.8664571875,462.4073716676,430.8920854961,312.0535375131,241.0575221148,237.0985027488,301.387850819,527.1170428969,143.1662580581,426.0776586782,286.9076546108,550.8595620823,221.2474663375,123.8808075681,135.9005856827,120.5381309228,448.9083511842,145.6146134845,554.0546668724], [85.5144472218,281.028874371,284.0801773466,413.4032371687,139.5031700376,402.6902227099,119.0014246959,337.4957710662,93.2718681256,428.9052698413,401.7032162209,333.4078594725,443.7934091548,200.8078375568,331.2847773569,334.2125152467,275.1315149865,85.0482899409,359.3038589096], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [293.4139987123,307.6271050296,535.6029131511,554.603611197,125.3438565009,483.9511994101,214.080476751,578.2539044696,263.9987433347,636.1360193165,181.908092888,455.5131552246,401.9597978622,338.2793980915,236.3370144828,271.753613844,524.2080370401,197.6368546854,595.7262564431], [558.8953614054,585.2596684973,320.4305648824,713.4362996923,653.8893743162,796.0510671335,569.8629952304,209.5507316436,595.6449871838,560.1674726838,944.9843801253,433.3547956776,935.9747444693,641.5225623928,864.6683983831,856.3101051855,287.8651143034,627.1027199756,185.8788120619], [85.5144472218,281.028874371,284.0801773466,413.4032371687,139.5031700376,402.6902227099,119.0014246959,337.4957710662,93.2718681256,428.9052698413,401.7032162209,333.4078594725,443.7934091548,200.8078375568,331.2847773569,334.2125152467,275.1315149865,85.0482899409,359.3038589096], [241.9573881545,591.5146374191,247.0428811074,157.6280413481,445.2935109156,249.8553281155,438.6438299364,383.9843889657,261.2760940082,114.9402284044,601.4368780507,587.2795003942,434.4385197215,193.06830737,442.6238343356,411.3861006297,301.6840049865,329.1649155322,415.4704772204], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [56.0921545309,412.902036059,297.5333736374,285.2234197985,229.0978201421,268.7955740074,247.0905749746,395.9514441317,44.7437460488,338.2824193583,395.5008744783,463.1932582293,338.2923921014,66.4697945551,267.8320107274,253.6805294308,316.1612918266,108.2976948333,423.7962776839], [149.069224813,330.4659773849,405.7336202326,415.857621564,107.5525917099,363.2905054212,174.8914587817,471.1684703815,116.4401301569,487.2408756833,270.6346720159,432.6556081728,342.2304358264,193.5419528876,205.910866661,218.5427544477,405.115908382,55.5139249773,493.5098106849], [274.5694298452,96.7226289451,410.2628080534,601.925053624,134.9665920098,580.0210174769,71.3817522608,401.550168412,274.0853649319,610.7307605977,417.1155703321,220.2964881385,576.7281021613,383.5528978686,429.3190667487,449.8773651853,375.0745230825,227.18718079,410.2061992824], [506.0241717405,326.4854047402,409.8962929486,784.3000425348,489.4131335064,819.3619468936,397.7367327795,288.6069229999,531.5142025687,696.982515423,785.2894182648,154.837343783,889.0230232811,622.6184289092,767.9143589574,776.809378851,348.3488226388,526.0186273986,265.7775144936], [241.9573881545,591.5146374191,247.0428811074,157.6280413481,445.2935109156,249.8553281155,438.6438299364,383.9843889657,261.2760940082,114.9402284044,601.4368780507,587.2795003942,434.4385197215,193.06830737,442.6238343356,411.3861006297,301.6840049865,329.1649155322,415.4704772204], [558.8953614054,585.2596684973,320.4305648824,713.4362996923,653.8893743162,796.0510671335,569.8629952304,209.5507316436,595.6449871838,560.1674726838,944.9843801253,433.3547956776,935.9747444693,641.5225623928,864.6683983831,856.3101051855,287.8651143034,627.1027199756,185.8788120619], [84.1613308649,366.0755579603,347.5622357908,348.9377235249,162.4652632626,311.1265884556,200.2677319322,428.3583411828,46.972086648,412.7667230572,330.8425129735,441.4889580375,332.5050956679,124.2758406757,227.4167663777,225.2157918285,355.2757434166,42.7389038973,453.4872794841], [549.0356987475,255.2266783435,525.7766913891,859.6659156619,468.4109650187,871.8262544252,387.1309149898,424.6423265084,565.2851620552,802.8818670808,741.0362188334,141.8487222428,903.4337380964,669.2337347976,762.230196629,780.1504197038,465.7267975823,540.0467590442,407.9058353089], [268.8985716026,420.2611575523,531.9174933887,456.3792450784,200.1916851086,368.247282995,288.7377950364,604.1175401502,231.7051320711,569.0711575642,147.840487193,547.7093040642,268.4236311164,263.2179126415,103.3685155017,138.5081452614,535.9683980951,186.0236419889,626.8571833509], [222.6805445533,200.8151058884,426.3483074066,535.0024197169,26.8171524372,494.6969750158,80.0218854537,452.0982350485,207.848632883,576.0980635994,313.8403872774,327.9726023246,470.0865570307,310.4827889028,318.833657707,341.3781656667,405.9378769806,145.4766865288,467.340684758], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728], [354.9148534124,56.2771011454,423.8016612392,680.5454988278,245.9604307269,672.9661814328,169.0279444122,377.9512647614,363.0717256688,662.431006858,523.693695328,119.4901089526,684.8565375156,471.8011149687,540.1464399033,559.4840894681,375.9414760633,326.8721031915,378.0031326213], [222.6805445533,200.8151058884,426.3483074066,535.0024197169,26.8171524372,494.6969750158,80.0218854537,452.0982350485,207.848632883,576.0980635994,313.8403872774,327.9726023246,470.0865570307,310.4827889028,318.833657707,341.3781656667,405.9378769806,145.4766865288,467.340684758], [220.3617818329,309.9700491566,469.0200061971,484.6479792943,89.4766428091,421.6463590237,180.2633872215,521.8217851177,189.8838618959,561.6988655724,218.6006822643,437.4749606078,366.2331003418,265.4364501641,209.2326397001,235.5221275124,462.2185339079,124.47379787,541.5726390728]] def distance (p,c): """R=6367445 res=R*acos(sin(radians(p.latitude))*sin(radians(c.latitude))+cos(radians(p.latitude))*cos(radians(c.latitude))*cos(radians(p.longitude-c.longitude)))""" if (res<=0): print("Probleme dans calcul distance") print(" producteur") print(p.name) print("Client") print(c.name) return 30000000000 return res def coeffPertes(p,c): """resistance lineique dune ligne HT en Ohm/mm 2""" rho=3/10**8 """section cable moyen ligne HT en mm 2""" section=500 """Resistance equivalente""" Req=rho*distance(p,c)/section """en ampere, intensite moyenne sur un HT""" I=400 if (p.region==c.region): """en Volt""" U=90*10**3 else: """en Volt""" U=400*10**3 """Pour probleme Combinatoire Ou 1-Req*I/U selon utilisation""" return Req*I/U def findCriticalDistance(TabProd, TabClient): distClient=[] referent=[] for i in range(len(TabClient)): mini=distance(TabProd[0],TabClient[i]) r=TabProd[0] print("je change") for p in range(len(TabProd)): print(TabProd[p].name) a=distance(TabProd[p],TabClient[i]) print(a) if a<=mini : mini=distance(TabProd[p],TabClient[i]) r=TabProd[p] print(r.name) distClient.append(mini) referent.append(r) """con=1 for c in range(len(TabClient)): for p in range(len(TabProd)): if (distance(TabProd[p],TabClient[c])<=distClient[c]): print("findCriticalDistance Chie") con=0 if(con==1): print("Cest bon, jai bien les bonnes distances") """ """print(distClient) for p in referent: print(p.name)""" maxi=distClient[0] for d in distClient: if(d>maxi): maxi=d return maxi def findCriticalClient(Producteur, TabClient): m=0 clientIndex=0 for i in range(len(TabClient)): if(distance(Producteur,TabClient[i])>distance(Producteur,TabClient[clientIndex])): clientIndex=i return TabClient[clientIndex].name def generateSetPerso(TabProd, TabClient): """Generer les sets de solutions possible de facon a ce que tout Client ait au moins un Set le couvrant""" D=findCriticalDistance(TabProd, TabClient) TabSet=[] for i in range(len(TabProd)): TabSetIteration=[] ClientIteration=[] for j in range(len(TabClient)): if(distance(TabProd[i],TabClient[j])<=D): ClientIteration.append(TabClient[j]) """Amelioration en triant ClientIteration""" while(len(ClientIteration)>0): d=findCriticalClient(TabProd[i],ClientIteration) TabSetIteration.append(S.Set(TabProd[i],ClientIteration)) del(ClientIteration[d]) for j in TabSetIteration: TabSet.append(j) return TabSet def countClientServed(TabSet): acc=0 for s in TabSet: acc+=len(s.TabClient) return acc def generateSetSimplified(TabProd, TabClient): """Generer les sets de solutions possible de facon a ce que tout Client ait au moins un Set le couvrant""" D=findCriticalDistance(TabProd, TabClient) TabSet=[] for i in range(0,len(TabProd)): ClientIteration=[] for j in range(len(TabClient)): if(distance(TabProd[i],TabClient[j])<=D): ClientIteration.append(TabClient[j]) """Amelioration en triant ClientIteration""" TabSet.append(S.Set(TabProd[i],ClientIteration)) print("Nombre de set") print(len(TabSet)) print("Nombre de client dans les sets") print(countClientServed(TabSet)) print("Nombre de client total") print(len(TabClient)) return TabSet def linearRelaxation(TabSet, TabClient): """To solve with cobyla algorithm the relaxed prb min sum(i) x(i)Cout(i) CT Pour tout j Sum (i:j)(Si) xi>=1 CT 0<=xi<=1 Doesn't work properly for big Sets """ def func(x): """To call with x an array of len(TabSet) length""" acc=0 for s in range(len(TabSet)): acc+=TabSet[s].coutglobal*x[s] return acc argsFunc=[] alpha=[] for i in range(len(TabSet)): alpha.append(TabSet[i].coutglobal) argsFunc=tuple(a for a in alpha) print(argsFunc) cons=[] def ctFun2(x,i): return x[i] def ctFun3(x,i): return x[i]+1 i=0 while(i<len(TabSet)): cons.append(ctFun2) i+=1 i=0 while(i<len(TabSet)): cons.append(ctFun3) i+=1 args=[] j=0 while(j<2): for i in range(len(TabSet)): args.append([i]) j+=1 print(len(cons)) print(len(args)) b=np.ones(len(TabSet)) """Creation des contraintes""" def ctFun(x,client,TabSet): acc=0 for i in range(len(TabSet)): acc+=TabSet[i].asClient(client)*x[i] return acc-1 for i in range(len(TabClient)): cons.append(ctFun) args.append([TabClient[i], TabSet]) print(len(cons)) print(len(args)) print(args) xopt=my_fmin_cobyla(func,b, cons,consargs=args) for k in range(len(xopt)): if(xopt[k]*log(len(TabClient))>1): xopt[k]=1 return xopt """ def linearRelaxation(TabSet, TabClient): To solve with simplex the relaxed prb min sum(i) x(i)Cout(i) CT Pour tout j Sum (i:j)(Si) xi>=1 CT 0<=xi<=1 def func(x): To call with x an array of len(TabSet) length return sum (TabSet[1:].coutglobal*x[1:]) def func_dev(x): a=zeros(len(x)) for i in range(len(x)): a[i]=TabSet[i].coutglobal return a Creation des contraintes cons=[{} for j in range(len(TabClient))] for j in range(len(TabClient)): cons[j]["type"]="inq" cons[j]["fun"]=lambda x:np.array(sum(TabSet[1:].asClient(TabClient[i])*x[1:])-1) cons[j]["jac"]=lambda x:np.array( TabSet[1:].asClient(TabClient[i]) for h in range(len(TabSet))) TESTER ARGS xopt=optimi.minimize(func, np.array( 1 for h in range(len(TabSet))), args=(0,1), jac=func_dev, constraints=cons , method='SLSQP', options={'disp': True}) for k in range(len(xopt)): if(xopt[k]*log(len(TabClient))>1): xopt[k]=1 return xopt """ def decisionToPickSet(TabProbaSet): """ 1.Generate a number between 0 and 1. 2. Walk the list substracting the probability of each item from your number. 3.Pick the item that, after substraction, took your number down to 0 or below. Complexity O(n)""" TabBooleanSet=np.zeros(len(TabProbaSet)) b=r.random() t=TabProbaSet for i in range(len(t)): t[i]+=b if (t[i]>=1): TabBooleanSet[i]=1 return TabBooleanSet def repairingFinal(TabSet, TabBooleanSet, TabClient): """ Insure that every Client as at minimum one Set covering it""" a=[] for i in range(len(TabBooleanSet)): if (TabBooleanSet[i]==1): for j in range(len(TabSet[i].TabClient)): a.append(TabSet[i].TabClient[j]) for i in range(len(TabClient)): cond=0 for j in range(len(a)): if (TabClient[i]==a[j]): cond=1 break if (cond==0): b=[] for k in range(len(TabBooleanSet)): if (TabBooleanSet[k]==0 & TabSet[k].asClient(i)): b.append(k) minb=TabSet[b[0]].coutglobal index=b[0] for k in range(len(b)): if (TabSet[b[k]].coutglobal<TabSet[b[0]].coutglobal): minb=TabSet[b[k]].coutglobal index=b[k] TabBooleanSet[index]=1 return TabBooleanSet # Interface to Constrained Optimization By Linear Approximation def my_fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0, rhoend=1e-10, iprint=2, maxfun=1000000): """ Minimize a function using the Contrained Optimization BY Linear Approximation (COBYLA) method Arguments: func -- function to minimize. Called as func(x, *args) x0 -- initial guess to minimum cons -- a list of functions that all must be >=0 (a single function if only 1 constraint) args -- extra arguments to pass to function consargs -- extra arguments to pass to constraints (default of None means use same extra arguments as those passed to func). Use () for no extra arguments. rhobeg -- reasonable initial changes to the variables rhoend -- final accuracy in the optimization (not precisely guaranteed) iprint -- controls the frequency of output: 0 (no output),1,2,3 maxfun -- maximum number of function evaluations. Returns: x -- the minimum """ err = "cons must be a list of callable functions or a single"\ " callable function." n = len(x0) if isinstance(cons, list): m = len(cons) for thisfunc in cons: if not callable(thisfunc): raise TypeError, err elif callable(cons): m = 1 cons = [cons] else: raise TypeError, "cons must be a list of callable functions or a single"\ " callable function." if consargs is None: consargs = args def calcfc(x, con): f = func(x, *args) k = 0 for constraints in cons: con[k] = constraints(x,*consargs[k]) k += 1 return f xopt = s._cobyla.minimize(calcfc, m=m, x=x0,rhobeg=rhobeg,rhoend=rhoend,iprint=iprint, maxfun=maxfun) return xopt def greedyAlgorithm(TabSet, TabClient): def lonelyClient(BoolTabSet,client): for s in range(len(TabSet)): if(BoolTabSet[s]*TabSet[s].asClient(client)==1): return 1 return 0 def existLonelyClient(BoolTabClient): for b in BoolTabClient: if (b==0): return 1 return 0 def priceTotalSet(BoolTabSet, Set): acc=0 for i in range(len(BoolTabSet)): acc+=BoolTabSet[i]*TabSet[i].coutglobal return Set.coutglobal/acc def findMinCost(BoolTabSet): index=0 while(index<len(BoolTabSet) and BoolTabSet[index]==1): index+=1 if(index==len(BoolTabSet)): print("It should be terminated") mini=TabSet[index].coutglobal for i in range(index,len(TabSet)): if(BoolTabSet[i]==0 and TabSet[i].coutglobal<mini): index=i mini=TabSet[i].coutglobal return index def findClient(client): for i in range(len(TabClient)): if (client.key==TabClient[i].key): return i return len(TabClient) """Test findClient""" acc=0 for i in range(len(TabClient)): if(findClient(TabClient[i])!=i): acc+=1 print("findClient Chie") BoolTabClient=np.zeros(len(TabClient)) BoolTabSet=np.zeros(len(TabSet)) PriceTabSet=np.zeros(len(TabSet)) while (existLonelyClient(BoolTabClient)): index=findMinCost(BoolTabSet) BoolTabSet[index]=1 for i in range(len(TabSet[index].TabClient)): BoolTabClient[findClient(TabSet[index].TabClient[i])]=1 return BoolTabSet """ def toPlotEdges(TabSet, TabBooleanSet): return any inforation needed to plot edges return ? """
Python
import FonctionSetCover as F class Set: """ Cette classe permet de construire des regroupements entre un Producteur et des clients potentiels. - Producteur (-index) -Consommateur[] -Cout global// qui compte l'approvisionnement des centrales + la mise en route a definir plus en detail. """ index=0 def __init__(self, producteur, tab): Set.index +=1 self.producteur=producteur self.TabClient=[] for i in tab: self.TabClient.append(i) s=producteur.coutlancement for i in tab: s+=F.coeffPertes(producteur,i)*producteur.cmwh self.coutglobal=s def asClient(self,client): for i in range(len(self.TabClient)): if (self.TabClient[i].key==client.key): return 1 return 0
Python
#!/usr/bin/env python # Current Cost Envir logger # Grabs Main Electricity, temperature and remote units # code located on http://code.google.com/p/my-jog-home # created from reference: http://naxxfish.eu/2012/electricity-usage-logging-with-currentcost-envir-and-a-raspberry-pi/ import sys sys.path.append('../xap') sys.path.append('../include') from xaplib import Xap from time import localtime, strftime, sleep from sp_keys import * import xml.etree.ElementTree as ET import os import serial import binascii import subprocess import re import syslog import eeml # pachube / cosm # API_KEY='moved to include file' COSM_API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = COSM_FEED_SHAWPAD) syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_SYSLOG) temperatureCurrent=0 temperaturePrevious=0 SensorCurrent=range(4) SensorPrevious=range(4) changed=0 readingsTaken=0 #Name, Sensor ID, COSM ID SensorList=[ ["Main", 0, 1], ["SqueezyPi", 2, 4], ["HotWaterTap", 1, 3], ["Washing Machine", 3, 6], ] # COSM feed ID for the envir temperature value COSM_ID_TEMP=2 syslog.syslog(syslog.LOG_INFO, 'Processing started') ser = serial.Serial('/dev/ttyUSB2',57600 ) # open up cosm feed pac = eeml.Pachube(COSM_API_URL, COSM_API_KEY) line = "" while 1: try: x = ser.read() line = line + x if (x == "\n"): # parse that line! tree = ET.fromstring(line) line = "" type = tree.find('type') if type is None or type.text != '1': print "Received non-realtime sensor packet: %s" % line continue sensor = int(tree.find('sensor').text) #print "\n --- Received packet from sensor %d" % sensor temp = tree.find('tmpr').text if tree.find('ch1') is not None: ch1 = tree.find('ch1') ch1_watts = int(ch1.find('watts').text) print "Sensor %d: %dW, %sC" % (sensor, ch1_watts, temp) if SensorPrevious[sensor]!=ch1_watts: SensorCurrent[sensor]=ch1_watts SensorPrevious[sensor]=ch1_watts changed=1 # Add data for COSM for element in SensorList: if element[1] == sensor: pac.update([eeml.Data(element[2], SensorCurrent[element[1]], unit=eeml.Watt())]) if temperaturePrevious!=temp: temperatureCurrent=temp temperaturePrevious=temp # changed=1 #- not interested in temp change to force COSM as it will get picked up on other change anyway # Add data for COSM pac.update([eeml.Data(COSM_ID_TEMP, temp, unit=eeml.Celsius())]) # Upload data to COSM every x samples if changed and ((readingsTaken % 10 ==0) or (readingsTaken<10)): print "New Values to COSM %d" % (readingsTaken %30) pac.put() changed=0 readingsTaken+=1 except: print "Issue with capture element" syslog.syslog(syslog.LOG_ERR, 'Exception thrown during loop')
Python
#!/usr/bin/env python # Water Solar Collector Readings Logger # Grabs information from the vbus console and post xap to the Network # code located on http://code.google.com/p/my-jog-home # reference code for vbusdecode from http://code.google.com/p/vbusdecode/ # reference code for hah/xap from http://code.google.com/p/livebox-hah/ import sys sys.path.append('../xap') sys.path.append('../include') from xaplib import Xap from time import localtime, strftime, sleep from sp_keys import * import serial import binascii import subprocess import re import syslog import eeml # sequence / process # uses vbusdecode compiled c from vbusdecode on google code projects (thanks) # check for new solar reading every 45 seconds # if values have changed from previous, post a new xapEvent # if no events have been posted for 3 new readings then post an xapInfo packet # need to generate heatbeat events - need to work out how often to send them # use TStats Feed for debug # need to keep some old values, so as not to dump event when no change in values pCol=0 pBottom=0 pTop=0 pPump=0 # pachube / cosm # API_KEY='moved to include file' COSM_API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = COSM_FEED_SHAWPAD) syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_SYSLOG) def solar(xap): global pBottom global pCol global pTop global pPump s = serial.Serial("/dev/ttyUSB1") # test - read 100 bytes from serial port and print out (non formatted, thus garbled line = s.read(100) # convert to ascii # print binascii.hexlify(line) # close the serial port as it won't be used for 5 secs s.close() # decode the line, at the moment, system calling the vbusdecode binary, # should really put the decode in python vb = subprocess.Popen(["./vbusdecode_pi", "0,15,0.1", "2,15,0.1", "4,15,0.1", "6,15,0.1", "8,7,1", "9,7,1"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) result = vb.communicate(line)[0] # make sure only one frame is present from decode # result = result[:26] # print result # split the results into their core parts if len(result)>20 : col, bottom, top, sp4, pump, sp1 = re.split('\ +',result,5) col=float(col) bottom=float(bottom) top=float(top) pump=float(pump) if pump>0 : pump="On" else : pump="Off" # adjust collector for -ve if col>600: print "Col -ve value: %2.1f\n" % col col=(col-6550.6)*-1 print "Captured reading: ", print "col=",col, " bot=",bottom, " top=",top, " pump=",pump, print "Sending xAPs.." # open up your cosm feed pac = eeml.Pachube(COSM_API_URL, COSM_API_KEY) # top msg = "input.state\n{\ntext=%2.1f\n}" % top try: if pTop!=top: xap.sendInstanceEventMsg( msg, "tanktop.temp") pac.update([eeml.Data(11, top, unit=eeml.Celsius())]) else: xap.sendInstanceInfoMsg( msg, "tanktop.temp") except: print "Failed to send xAP, network may be down" # bottom msg = "input.state\n{\ntext=%2.1f\n}" % bottom try: if pBottom!=bottom: xap.sendInstanceEventMsg( msg, "tankbot.temp") pac.update([eeml.Data(10, bottom, unit=eeml.Celsius())]) else: xap.sendInstanceInfoMsg( msg, "tankbot.temp") except: print "Failed to send xAP, network may be down" # collector temp msg = "input.state\n{\ntext=%2.1f\n}" % col try: if pCol!=col: xap.sendInstanceEventMsg( msg, "collector.temp") pac.update([eeml.Data(9, col, unit=eeml.Celsius())]) else: xap.sendInstanceInfoMsg( msg, "collector.temp") except: print "Failed to send xAP, network may be down" # pump state msg = "input.state\n{\nstate=%s\n}" % pump try: if pPump!=pump: xap.sendInstanceEventMsg( msg, "pump") pac.update([eeml.Data(12, pump, unit=eeml.Unit('Binary','derivedUnits','B'))]) else: xap.sendInstanceInfoMsg( msg, "pump") except: print "Failed to send xAP, network may be down" pTop=top pBottom=bottom pCol=col pPump=pump # send data to cosm try: pac.put() except: print "Failed to update COSM, network may be down" else: print "No value captured" # wait another 45 seconds before attempting another read sleep(45) syslog.syslog(syslog.LOG_INFO, 'Processing started') Xap("F4060F01","shawpad.ujog.solar").run(solar)
Python
# # # # import serial from struct import pack import time import sys import os sys.path.append('../xap') from xaplib import Xap from stats_defn import * from hm_constants import * from hm_utils import * # these will be crated as an array # def SetxAPNodeTemp(temperature, serport, xap, holdtime=0): # def SetNodeTemp(temperature, serport, holdtime=0): # def GetxAPNodeTemp(temperature, serport, xap, holdtime=0): # def GetNodeTemp(serport) # def GetTargetNodeTemp(serport) # def readTStatStatus(serport,force=0) # def mapdata(datal): class thermostat: " class to handle data set for each instance of a t-stat" def __init__(self, address, shortName, longName, protocol, instanceID, UID): serf.initialised = 0 # flag to indicate that initial data set not read yet self.definedaddress = address self.xAPInstanceID = instanceID self.xAPUID = UID self.protocol = protocol self.shortName = shortName self.longName = longName self.DATAOFFSET = 9 self.GET_TEMP_CMD=38 self.SET_TEMP_CMD=18 # t-stat payload data self.off=0 self.demand=0 # current demand i.e. flame on self.currenttemp=0 self.lastxAPcurentTemp=0 self.targettemp=0 self.sensormode=0 self.model =0 self.tempformat =0 self.frostprotectionenable =0 self.frosttemp =0 ## need to add the rest of the data structure....... # set demand temp and post xAP message # checking for demand changes and using event / info appropriately def SetxAPNodeTemp(temperature, serport, xap, holdtime=0): # create the xap message ready msg = "input.state\n{\ntext=%2.1f\n}" % temperature try: # event or info? if (temperature!=self.targettemp): SetNodeTemp(temperature, serport, holdtime) # now temp set handle the xap message post ## TODO: need extra handler as the xap handler could have error and if we are here then the t-stat has already had it's demand temperature updated xap.sendInstanceEventMsg( msg, self.xAPInstanceid ) self.targettemp=temperature else: # no need to send new request to t-stat as the current demand is still accurate xap.sendInstanceInfoMsg( msg, self.xAPInstanceid ) except: print "Failure to SetxAPNodeTemp(%d) on tstat address %d" % (temperature, self.definedaddress) raise "SetxAPNodeTemp(%d) failed for node: %d" % (temperature, self.definedaddress) # set demand temperature with optional hold time def SetNodeTemp(temperature, serport, holdtime=0): payload = [temperature] msg = hmFormMsgCRC(self.definedaddress, node[SL_CONTR_TYPE], MY_MASTER_ADDR, FUNC_WRITE, SET_TEMP_CMD, payload) print msg string = ''.join(map(chr,msg)) if (hm_sendwritecmd(self.definedaddress, string, serport)==1): print "Failure to SetNodeTemp to %d on tstat address %d" % (temperature,self.definedaddress) raise "SetNodeTemp failed for node: %d" % self.definedaddress else: self.roomsettemp = temperature # set demand temp and post xAP message # checking for demand changes and using event / info appropriately def GetxAPNodeTemp(serport, xap): try: GetNodeTemp(serport) # now temp get handle the xap message post # create the xap event msg = "input.state\n{\nstate=%d\ntext=%2.1f\n}" % (self.demand, self.currenttemp) #print msg # event or info? if (self.currenttemp!=self.lastxAPcurentTemp): xap.sendInstanceEventMsg( msg, self.xAPInstanceid ) self.lastxAPcurentTemp=self.currenttemp else: xap.sendInstanceInfoMsg( msg, self.xAPInstanceid ) except: print "Failure to GetxAPNodeTemp() on tstat address %d" % (self.definedaddress) raise "GetxAPNodeTemp() failed for node: %d" % (self.definedaddress) return self.currenttemp # get current t-stat temperature def GetNodeTemp(serport): ReadTStatStatus(serport) print "Current Temperature: %.1f" % self.currenttemp return self.currenttemp # get target t-stat temperature def GetTargetNodeTemp(serport): ReadTStatStatus(serport) print "Target Temperature: %.1f" % self.targettemp return self.targettemp def ReadTStatStatus(serport,force=0): # read and update all the status for the t-stat also # TODO: use a timer, if cache data still current for 3 mins, the don't read, just use cached data payload = [] try: payload = hm_sendreadcmd(self.definedaddress, serport) # parse the payload to extract the current temp self.mapdata(payload) except: print "Failure to ReadTStatStatus() on tstat address %d" % (self.definedaddress) raise "ReadTStatStatus failed for node: %d" % self.definedaddress # call this routine with a datablock read from the serial port to update all the status in the class def mapdata(datal): "check the address in the payload is this instance address" address = datal[11+ DATAOFFSET] if (self.definedaddress!=address): raise "Invalid Address in payload provided (%d), should be %d for this class instance" % (address, self.definedaddress) self.model = datal[4+ DATAOFFSET] # (DT/DT-E/PRT/PRT-E) (00/01/02/03) self.tempformat = datal[5+ DATAOFFSET] # C=0 F=1 self.frostprotectionenable = datal[7+ DATAOFFSET] self.frosttemp = datal[17+ DATAOFFSET] # frost protect temperature default 12 #cal_h=datal[8+ DATAOFFSET] #cal_l = datal[9+ DATAOFFSET] #self.caloffset = (cal_h*256 + cal_l) self.outputdelay = datal[10+ DATAOFFSET] self.optimstart = datal[14+ DATAOFFSET] self.rateofchange = datal[15+ DATAOFFSET] self.targettemp = datal[18+ DATAOFFSET] self.off = datal[21+ DATAOFFSET] self.keylock = datal[22+ DATAOFFSET] self.runmode = datal[23+ DATAOFFSET] holidayhourshigh = datal[24+ DATAOFFSET] holidayhourslow = datal[25+ DATAOFFSET] self.holidayhours = (holidayhourshigh*256 + holidayhourslow) tempholdminshigh = datal[26+ DATAOFFSET] tempholdminslow = datal[27+ DATAOFFSET] self.tempholdmins = (tempholdminshigh*256 + tempholdminslow) # if sensormode is 0 then use air sensor, otherwise 2 is floortemp # these are the only 2 we are using in our system self.sensormode = datal[13+ DATAOFFSET] # air / remote / floor if self.sensormode==0: tempsenseoffset+=2 else: tempsenseoffset=0 temphigh = datal[30+tempsenseoffset+ DATAOFFSET] templow = datal[31+tempsenseoffset+ DATAOFFSET] self.currenttemp = (temphigh*256 + templow)/10.0 self.errcode = datal[34+ DATAOFFSET] self.demand = datal[35+ DATAOFFSET] # 1 = currently heating self.currentday = datal[36+ DATAOFFSET] self.currenthour = datal[37+ DATAOFFSET] self.currentmin = datal[38+ DATAOFFSET] self.currentsec = datal[39+ DATAOFFSET] self.progmode = datal[16+ DATAOFFSET] # 0 = 5/2 self.wday_t1_hour = datal[40+ DATAOFFSET] self.wday_t1_mins = datal[41+ DATAOFFSET] self.wday_t1_temp = datal[42+ DATAOFFSET] self.wday_t2_hour = datal[43+ DATAOFFSET] self.wday_t2_mins = datal[44+ DATAOFFSET] self.wday_t2_temp = datal[45+ DATAOFFSET] self.wday_t3_hour = datal[46+ DATAOFFSET] self.wday_t3_mins = datal[47+ DATAOFFSET] self.wday_t3_temp = datal[48+ DATAOFFSET] self.wday_t4_hour = datal[49+ DATAOFFSET] self.wday_t4_mins = datal[50+ DATAOFFSET] self.wday_t4_temp = datal[51+ DATAOFFSET] self.wend_t1_hour = datal[52+ DATAOFFSET] self.wend_t1_mins = datal[53+ DATAOFFSET] self.wend_t1_temp = datal[54+ DATAOFFSET] self.wend_t2_hour = datal[55+ DATAOFFSET] self.wend_t2_mins = datal[56+ DATAOFFSET] self.wend_t2_temp = datal[57+ DATAOFFSET] self.wend_t3_hour = datal[58+ DATAOFFSET] self.wend_t3_mins = datal[59+ DATAOFFSET] self.wend_t3_temp = datal[60+ DATAOFFSET] self.wend_t4_hour = datal[61+ DATAOFFSET] self.wend_t4_mins = datal[62+ DATAOFFSET] self.wend_t4_temp = datal[63+ DATAOFFSET]
Python
import sys import signal import serial from time import localtime, strftime, sleep import binascii import subprocess # thread mutexs serialmutex=0 xapmutex=0 class TimeoutException(Exception): pass # use the mutex variable to control access to the serial portdef obtainMutexSerialAccess(): def obtainMutexSerialAccess(serport): global serialmutex def timeout_handler(signum, frame): print "Timeout exeption while waiting for serial mutex" raise TimeoutException() signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(30) # allow 30 secs for the other process to complete before timing out while (serialmutex==1): # do nothing other than checking for timeout x=0 # mutext now been released, so grab it and open the serial port serialmutex=1 serport.open() def releaseMutexSerialAccess(serport): global serialmutex serport.close() serialmutex=0
Python
# # Ian Shaw 2012 # # Based on code set from Neil Trimboy (http://code.google.com/p/heatmiser-monitor-control) # # Functions to support heatmiser setup, these functions will be used by the XAP handler # hm_lock(on/off,nodes=StatList) # hm_setTemp(temp,nodes=StatList) # hm_setTemp(temp,nodeName<string>)) # hm_getTemp(nodes) # import serial from struct import pack import time import sys import os from stats_defn import * from hm_constants import * from hm_utils import * DATAOFFSET = 9 # hm_lock(state, node=StatList) # inputs: state: string 'lock'/'unlock' # nodes: will be the array of the tstats that need operating on # return true for good status return def hm_lock(state, nodes, serport) : err=0 if (state=='lock') : state=KEY_LOCK_LOCK else : state = KEY_LOCK_UKLOCK for node in nodes : err += hmKeyLock(node, state, serport) return err # hm_setTemp(temp, nodes) # inputs: temp: temperature value to set # nodes: will be the array of the tstats that need operating on # return true for good status return def hm_setTemp(temp, nodes, serport) : err=0 for node in nodes : err += hm_SetNodeTemp(temp, node, serport) return err # hm_SetNodeTemp(temp, node, serport) # set individual node temperature # node is the array element from the StatList structure SET_TEMP_CMD=18 def hm_SetNodeTemp(temperature, node, serport) : """hm_SetNodeTemp(temp, node, serport): set individual node temperature""" err=0 payload = [temperature] msg = hmFormMsgCRC(node[0], node[SL_CONTR_TYPE], MY_MASTER_ADDR, FUNC_WRITE, SET_TEMP_CMD, payload) print msg string = ''.join(map(chr,msg)) err = hm_sendwritecmd(node[0], string, serport) if (err==1) : print "Failure to SetNodeTemp to %d on tstat address %d" % (temperature,node[0]) return err # hm_GetNodeTemp(node, serport) # gets and returns individual node temperature # node is the array element from the StatList structure GET_TEMP_CMD=38 def hm_GetNodeTemp(node, serport) : """hm_GetNodeTemp(node, serport) : get node temp and return it""" err=0 payload = [] temperature=0.0 try: payload = hm_sendreadcmd(node[SL_ADDR], serport) except: print "Failure to GetNodeTemp() on tstat address %d" % (node[SL_ADDR]) err=1 if (err==0) : # parse the payload to extract the current temp intairtemphigh = payload[32+ DATAOFFSET] intairtemplow = payload[33+ DATAOFFSET] temperature = (intairtemphigh*256 + intairtemplow)/10.0 print "Temperature: %.1f" % temperature else: assert 0, "hm_GetNodeTemp failed for node: %d" % node[SL_ADDR] return temperature # generic function for sending a write command and validating the response # nodeAddress is the tstat communication address # message is the complete payload including crc def hm_sendwritecmd(nodeAddress, message, serport, protocol=HMV3_ID) : """generic function for sending a write command and validating the response""" err=0 # print serport try: written = serport.write(message) # Write the complete message packet except serial.SerialTimeoutException, e: s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = [] datal = datal + (map(ord,byteread)) if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, nodeAddress, FUNC_WRITE, 2, datal) == False): err = 1; print "OH DEAR BAD RESPONSE" return err # generic function for sending a read command, validating and returning the buffer def hm_sendreadcmd(nodeAddress, serport, protocol=HMV3_ID) : """generic function for sending a read command and validating the response. The entire read block is then returned for parsing""" # @todo parse the read block into a structure err=0 start_low = 0 start_high = 0 read_length_high = (RW_LENGTH_ALL & 0xff) read_length_low = (RW_LENGTH_ALL >> 8) & 0xff data = [nodeAddress, 0x0a, MY_MASTER_ADDR, FUNC_READ, start_low, start_high, read_length_low, read_length_high] #print data crc = crc16() data = data + crc.run(data) print data string = ''.join(map(chr,data)) try: written = serport.write(string) # Write a string except serial.SerialTimeoutException, e: sys.stderr.write("Write timeout error: %s\n" % (e)) s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) err += 1 # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode, this does not yet supt 7 day #print "Bytes read %d" % (len(byteread) ) #TODO checking for length here can be removed if (len(byteread)) == 75: print "Correct length reply received" else: print "Incorrect length reply %s" % (len(byteread)) s= "%s : Controller %2d : Incorrect length reply : %s\n" % (localtime, nodeAddress, len(byteread)) sys.stderr.write(s) err += 1 # TODO All this should only happen if correct length reply #Now try converting it back to array datal = [] datal = datal + (map(ord,byteread)) #print "Going to verify CRC" #print datal if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, nodeAddress, FUNC_READ, 75, datal) == False): err += 1 #print "Verification done: %d" % (err) if ((err > 0) or ((len(byteread)<>75) and (len(byteread)<>120)) ): assert 0, "Invalid Block Read from sendreadcmd() for node %d" % nodeAddress # Should really only be length 75 or TBD at this point as we shouldnt do this if bad resp # @todo define magic number 75 in terms of header and possible payload sizes # @todo value in next line of 120 is a wrong guess return datal
Python
# # Ian Shaw # # Debug script to set temperature on all array t-stats # import serial from struct import pack import time import sys import os from stats_defn import * from hm_constants import * from hm_utils import * from hm_controlfuncs import * problem = 0 #sys.stderr = open('errorlog.txt', 'a') # Redirect stderr serport = serial.Serial() serport.port = S_PORT_NAME serport.baudrate = 4800 serport.bytesize = serial.EIGHTBITS serport.parity = serial.PARITY_NONE serport.stopbits = serial.STOPBITS_ONE serport.timeout = 3 try: serport.open() except serial.SerialException, e: s= "%s : Could not open serial port %s: %s\n" % (localtime, serport.portstr, e) sys.stderr.write(s) problem += 1 #mail(you, "Heatmiser TempSet Error ", "Could not open serial port", "errorlog.txt") sys.exit(1) print "%s port configuration is %s" % (serport.name, serport.isOpen()) print "%s baud, %s bit, %s parity, with %s stopbits, timeout %s seconds" % (serport.baudrate, serport.bytesize, serport.parity, serport.stopbits, serport.timeout) #good = [0,0,0,0,0,0,0,0,0,0,0,0,0] # TODO one bigger than size required YUK #bad = [0,0,0,0,0,0,0,0,0,0,0,0,0] badresponse = range(12+1) #TODO hardcoded 12 here! YUK temp = 23 # CYCLE THROUGH ALL CONTROLLERS for controller in StatList: loop = controller[0] #BUG assumes statlist is addresses are 1...n, with no gaps or random print print "Setting Temperature to %d for address %2d in location %s *****************************" % (temp, loop, controller[2]) badresponse[loop] = 0 tstat = controller # pass through the the tstat array in the statlist hm_SetNodeTemp(temp, tstat, serport) time.sleep(2) # sleep for 2 seconds before next controller #END OF CYCLE THROUGH CONTROLLERS print serport serport.close() # close port print "Port is now %s" % serport.isOpen()
Python
# # Neil Trimboy 2011 # # Protocol for each controller HMV2_ID = 2 HMV3_ID = 3 BYTEMASK = 0xff # Constants for Methods # Passed to hmVerifyMsgCRCOK when message is of type FUNC_WRITE DONT_CARE_LENGTH = 1 # # HM Version 3 Magic Numbers # # Master must be in range [0x81,0xa0] = [129,160] MASTER_ADDR_MIN = 0x81 MASTER_ADDR_MAX = 0xa0 # Define magic numbers used in messages FUNC_READ = 0 FUNC_WRITE = 1 BROADCAST_ADDR = 0xff RW_LENGTH_ALL = 0xffff KEY_LOCK_ADDR = 22 HOL_HOURS_LO_ADDR = 24 HOL_HOURS_HI_ADDR = 25 CUR_TIME_ADDR = 43 KEY_LOCK_UNLOCK = 0 KEY_LOCK_LOCK = 1 # # HM Version 2 Magic Numbers # # TODO
Python
from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(5, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(18, GPIO.OUT) GPIO.output(5, GPIO.LOW) GPIO.output(16, GPIO.LOW) GPIO.output(18, GPIO.HIGH) sleep(3) GPIO.cleanup()
Python
# # Original: Neil Trimboy 2011 # Updated for Shawpad configuration: Ian Shaw # from hm_constants import * import serial # Master Address MY_MASTER_ADDR = 0x81 # Port S_PORT_NAME = '/dev/ttyUSB0' COM_PORT = S_PORT_NAME COM_BAUD = 4800 COM_SIZE = serial.EIGHTBITS COM_PARITY = serial.PARITY_NONE COM_STOP = serial.STOPBITS_ONE COM_TIMEOUT = 3 # A list of controllers # Adjust the number of rows in this list as required # Items in each row are : # Controller Address, ShortName, LongName, Controller Type, Graph Colour, xAP_Instance, xAP UID, T-Stat available bool, COSM ID StatList = [ [1, "Kit", "Kitchen", HMV3_ID, "A020F0", "kitchen.temp", "F4061102", 1, 4], [2, "Brk", "Breakfast Bar", HMV3_ID, "D02090", "breakfastbar.temp", "F4061103", 1, 5], [5, "Din", "Dining", HMV3_ID, "FF4500", "dining.temp","F4061104", 1, 2], #[6, "Liv", "Living", HMV3_ID, "FF8C00", "living.temp", "F4061105", 0, 10], #[7, "Sit", "Sitting", HMV3_ID, "FF8C00", "sitting.temp","F4061106", 0, 13], #[8, "Play", "Playroom", HMV3_ID, "32CD32", "playroom.temp","F4061107", 0, 9], [3, "Bed1", "Our Bedroom", HMV3_ID, "FFD700", "bedroom1.temp","F4061108", 1, 2], [4, "Ens1", "Our Ensuite", HMV3_ID, "6B8E23", "ensuite1.temp", "F4061109", 1, 3], #[9, "Bed2", "Chloe's Bedroom", HMV3_ID, "1E90FF", "bedroom2.temp","F4061110", 0, 7], [10, "Bed3", "Ethan's Bedroom", HMV3_ID, "6A5ACD", "bedroom3.temp","F4061111", 1, 8], #[11, "Bed4", "Loft Room", HMV3_ID, "00FA9A", "bedroom4.temp","F4061112", 0, 11], #[12, "Ens4", "Ensuite Loft", HMV3_ID, "00FA9A", "ensuite4.temp","F4061113", 0, 0], #[13, "Study", "Study", HMV3_ID, "00FA9A", "study.temp", "F4061114", 0, 12], #[14, "Bath", "Bathroom", HMV3_ID, "D2691E", "bathroom.temp","F4061115", 0, 0], #[15, "BTow", "Bathroom Towel", HMV3_ID, "00FA9A", "bathtowel.temp","F4061116", 0, 0], #[16, "Lob", "Lobby", HMV3_ID, "00FA9A", "lobby.temp","F4061117", 0, 0], #[17, "Clk", "Cloak Room", HMV3_ID, "00FA9A", "cloakroom.temp","F4061118", 0, 0], #[18, "Dry", "Drying Rail", HMV3_ID, "00FA9A", "drying.temp","F4061119", 0, 0], #[19, "Hall", "Hallway", HMV3_ID, "00FA9A", "hallway.temp","F4061120", 0 0], ] # Named indexing into StatList SL_ADDR = 0 SL_SHRT_NAME = 1 SL_LONG_NAME = 2 SL_CONTR_TYPE = 3 SL_GRAPH_COL = 4 SL_XAP_INSTANCE = 5 SL_XAP_UID = 6 SL_STAT_PRESENT = 7 SL_COSM_ID = 8
Python
#!/usr/bin/env python # Heating System handler # loop manages polling of Heatmiser Thermostats and handle xAP events # listens for xAP events and event slices in xAP / Thermostat updates # code located on http://code.google.com/p/flubber-hah # reference code for heatmiser from http://code.google.com/p/heatmiser-control # reference code for hah/xap from http://code.google.com/p/livebox-hah/ import sys import signal import serial sys.path.append('../xap') from xaplib import Xap from time import localtime, strftime, sleep import binascii import subprocess import re from struct import pack import os import syslog from data_types import * from stats_defn import * from hm_constants import * from hm_utils import * from hm_controlfuncs import * from xap_handle_heating_requests import * from fl_support import * serport = serial.Serial() serport.port = S_PORT_NAME serport.baudrate = 4800 serport.bytesize = serial.EIGHTBITS serport.parity = serial.PARITY_NONE serport.stopbits = serial.STOPBITS_ONE serport.timeout = 3 tstats =[] tstats.append(thermostat(1, "Kit", "Kitchen", HMV3_ID, "kitchen.temp", "F4061102")) temperaturesCurrent=range(15) temperaturesPrevious=range(15) badresponse=range(15) serialReadsGood=0 serialReadsBad=0 # debug / logging readingsTaken=0 syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_SYSLOG) def readStat(tstat, xap): global serport temp = -1 grabbedMutex=0 # 1 - read the t-stat try: # first wait to make sure no other thread is using the serial obtainMutexSerialAccess(serport) grabbedMutex=1 temp = tstat.GetxAPNodeTemp(serport, xap) print "\nRead Temperature for address %2d in location %s as %2.1f *****************************" % (tstat.address, tstat.longName, temp) except serial.SerialException, e: s= "%s : Could not open serial port %s, wait until next time for retry: %s\n" % (localtime, serport.portstr, e) sys.stderr.write(s) temp=-1 except: # leave temperaturesCurrent[loop] unaffected, therefore reusing previous value print "\nException caught while reading temp for location %s, moving on to next device **********" % (tstat.longName) temp=-1 # make sure we close the serial port before moving on but only if we grabbed mutex in the first place if grabbedMutex: releaseMutexSerialAccess(serport) return temp def heatingHandler(xap): global readingsTaken global temperaturesCurrent global temperaturesPrevious global badresponse global xapmutex global serialReadsGood global serialReadsBad global tstats # normal operation iterate through controllers in StatList, reading their status for controller in tstats: print "Starting: %s...." % controller.longName #before next step, check for any events that need servicing servicexAPStack(xap) loop = controller.address #BUG assumes statlist is addresses are 1...n, with no gaps or random tstat = controller # pass through the the tstat array in the statlist # 1 - read the t-stat # Only read the t-stat if this thermal element actually has a t-stat #if tstat[SL_STAT_PRESENT]: try: readStat(tstat,xap) except: serialReadsBad+=1 continue #bad read, so no message to send, skip to next in list serialReadsGood+=1 #before next step, check for any events that need servicing servicexAPStack(xap) time.sleep(1) # sleep between elements readingsTaken+=1 if readingsTaken % 10: syslog.syslog(syslog.LOG_INFO, 'logged:%d stat looops - Good:%d, Bad:%d' % (readingsTaken, serialReadsGood, serialReadsBad)) # wait another 30 seconds before attempting another read sleep(15) syslog.syslog(syslog.LOG_INFO, 'Processing started') #while(1): # try: Xap("F4061101","shawpad.rpi.heating").run(heatingHandler) # except: # syslog.syslog(syslog.LOG_ERR, 'Xap Crash')
Python
# # Neil Trimboy 2011 # # Sets current time/date to all controllers # # Despite Heatmiser V3 protocol document stating that current day/h/m/s is on 4 separate addresses [43,46] # Tests showed that it was not possible to write to individual value anf that all 4 values must be written in a single command import serial from struct import pack import time import sys import os from stats_defn import * from hm_constants import * from hm_utils import * #from comms_settings import * # CODE STARTS HERE problem = 0 #ferr = open('errorlog2.txt', 'a') #sys.stderr = open('errorlog.txt', 'a') # Redirect stderr # Generate a RFC2822 format date # This works with both Excel and Timeline localtime = time.asctime( time.localtime(time.time())) polltime = time.time() polltimet = time.localtime(polltime) localtime = time.strftime("%d %b %Y %H:%M:%S +0000", polltimet) localday = time.strftime("%w", polltimet) serport = serial.Serial() serport.port = COM_PORT serport.baudrate = COM_BAUD serport.bytesize = COM_SIZE serport.parity = COM_PARITY serport.stopbits = COM_STOP serport.timeout = COM_TIMEOUT try: serport.open() except serial.SerialException, e: s= "%s : Could not open serial port %s: %s\n" % (localtime, serport.portstr, e) sys.stderr.write(s) problem += 1 #mail(you, "Heatmiser TimeSet Error ", "Could not open serial port", "errorlog.txt") sys.exit(1) print "%s port configuration is %s" % (serport.name, serport.isOpen()) print "%s baud, %s bit, %s parity, with %s stopbits, timeout %s seconds" % (serport.baudrate, serport.bytesize, serport.parity, serport.stopbits, serport.timeout) good = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] # TODO one bigger than size required YUK #bad = [0,0,0,0,0,0,0,0,0,0,0,0,0] def setTime(controller, serport): global good loop = controller[SL_ADDR] #BUG assumes statlist is addresses are 1...n, with no gaps or random print "Testing control %2d in %s *****************************" % (loop, controller[SL_LONG_NAME]) try: if hmUpdateTime(controller, serport)==0: good[loop] = 1 #once set correctly flag it, such that we don't call again during retry loop except: print "Error setting time for %s at address %2d, moving on" % (controller[SL_LONG_NAME], loop) time.sleep(2) # sleep for 2 seconds before next controller # create a 5 time retry loop for retry in range(5): # CYCLE THROUGH ALL CONTROLLERS for controller in StatList: if good[controller[SL_ADDR]]==0: setTime(controller,serport) #END OF CYCLE THROUGH CONTROLLERS serport.close() # close port print "Port is now %s" % serport.isOpen() #ferr.close() #if (problem > 0): #mail(you, "Heatmiser TimeSet Error ", "A Problem has occurred", "errorlog.txt")
Python
#!/usr/bin/env python # Heatmiser Thermostats Polling # Polls the list of TStats and sends out current temperatures for every stat # Polling by default once per minute # code located on http://code.google.com/p/flubber-hah # reference code for vbusdecode from http://code.google.com/p/heatmiser-control # reference code for hah/xap from http://code.google.com/p/livebox-hah/ import sys import signal import serial sys.path.append('../xap') sys.path.append('../include') from xaplib import Xap from time import localtime, strftime, sleep import binascii import subprocess import re from struct import pack import os import syslog import eeml from stats_defn import * from hm_constants import * from hm_utils import * from hm_controlfuncs import * from xap_handle_heating_requests import * from sp_keys import * serport = serial.Serial() serport.port = S_PORT_NAME serport.baudrate = 4800 serport.bytesize = serial.EIGHTBITS serport.parity = serial.PARITY_NONE serport.stopbits = serial.STOPBITS_ONE serport.timeout = 3 # TODO: remove hardcoded size temperaturesCurrent=range(15) temperaturesPrevious=range(15) badresponse=range(15) serialReadsGood=0 serialReadsBad=0 # thread serialmutex=0 xapmutex=0 # COSM variables. COSM_API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = COSM_FEED_THERMOSTATS) # debug / logging readingsTaken=0 syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_SYSLOG) class TimeoutException(Exception): pass # use the mutex variable to control access to the serial portdef obtainMutexSerialAccess(): def obtainMutexSerialAccess(serport): global serialmutex def timeout_handler(signum, frame): print "Timeout exeption while waiting for serial mutex" raise TimeoutException() signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(30) # allow 30 secs for the other process to complete before timing out while (serialmutex==1): # do nothing other than checking for timeout x=0 # mutext now been released, so grab it and open the serial port serialmutex=1 serport.open() def releaseMutexSerialAccess(serport): global serialmutex serport.close() serialmutex=0 def readStat(tstat): global serport temp = -1 grabbedMutex=0 # 1 - read the t-stat try: # first wait to make sure no other thread is using the serial obtainMutexSerialAccess(serport) grabbedMutex=1 temp = hm_GetNodeTemp(tstat, serport) print "\nRead Temperature for address %2d in location %s as %2.1f *****************************" % (tstat[0], tstat[SL_LONG_NAME], temp) except serial.SerialException, e: s= "%s : Could not open serial port %s, wait until next time for retry: %s\n" % (localtime, serport.portstr, e) sys.stderr.write(s) temp=-1 except: # leave temperaturesCurrent[loop] unaffected, therefore reusing previous value print "\nException caught while reading temp for location %s, moving on to next device **********" % (tstat[SL_LONG_NAME]) temp=-1 # make sure we close the serial port before moving on but only if we grabbed mutex in the first place if grabbedMutex: releaseMutexSerialAccess(serport) return temp def heatingHandler(xap): global readingsTaken global temperaturesCurrent global temperaturesPrevious global badresponse global xapmutex global serialReadsGood global serialReadsBad # normal operation iterate through controllers in StatList, reading their status # open up cosm feed pac = eeml.Pachube(COSM_API_URL, COSM_API_KEY) # iterate through controllers in StatList for controller in StatList: print "Starting: %s...." % controller[SL_LONG_NAME] #before next step, check for any events that need servicing servicexAPStack(xap) loop = controller[0] #BUG assumes statlist is addresses are 1...n, with no gaps or random badresponse[loop] = 0 tstat = controller # pass through the the tstat array in the statlist # 1 - read the t-stat # Only read the t-stat if this thermal element actually has a t-stat if tstat[SL_STAT_PRESENT]: t=readStat(tstat) if t==-1: serialReadsBad+=1 continue #bad read, so no message to send, skip to next in list serialReadsGood+=1 temperaturesCurrent[loop]=t #before next step, check for any events that need servicing servicexAPStack(xap) # create the xap event msg = "input.state\n{\nstate=on\ntext=%2.1f\n}" % temperaturesCurrent[loop] #print msg # use an exception handler; if the network is down this command will fail # make sure to send an event or info, depdending on previous sent message value try: if temperaturesCurrent[loop] != temperaturesPrevious[loop]: # Send the xap message xap.sendInstanceEventMsg( msg, controller[SL_XAP_INSTANCE] ) # Upload temperature to COSM pac.update([eeml.Data(controller[SL_COSM_ID], temperaturesCurrent[loop], unit=eeml.Celsius())]) pac.put() temperaturesPrevious[loop] = temperaturesCurrent[loop] #print("event message") else: # send info message as no state change xap.sendInstanceInfoMsg( msg, controller[SL_XAP_INSTANCE] ) #print("info messge") except: print "Failed to send xAP/COSM, network may be down" # 3 - check to service any pending xap events # ............... time.sleep(1) # sleep for 30 seconds before next controller, while the stat list is small, 30sec periods are quick enough readingsTaken+=1 if readingsTaken % 50 == 0: syslog.syslog(syslog.LOG_INFO, 'logged:%d stat looops - Good:%d, Bad:%d' % (readingsTaken, serialReadsGood, serialReadsBad)) # wait another 30 seconds before attempting another read sleep(15) def checkHeatingMessage(xap): msg = "11" nummsg = 0 while len(msg)>1: msg = xap.receive() print "Message Length: %d" % len(msg) if len(msg)>0: print msg nummsg+=1 print "Num messages in block: %d" % nummsg sleep(10) syslog.syslog(syslog.LOG_INFO, 'Processing started') #while(1): # try: Xap("F4061101","shawpad.rpi.heating").run(heatingHandler) #Xap("F4061102","shawpad.rpi.heating").run(checkHeatingMessage) # except: # syslog.syslog(syslog.LOG_ERR, 'Xap Crash')
Python
# # Neil Trimboy 2011 # Assume Pyhton 2.7.x # import serial from struct import pack import time import sys import os import shutil from datetime import datetime # Import our own stuff from stats_defn import * from hm_constants import * # Believe this is known as CCITT (0xFFFF) # This is the CRC function converted directly from the Heatmiser C code # provided in their API class crc16: LookupHigh = [ 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x81, 0x91, 0xa1, 0xb1, 0xc1, 0xd1, 0xe1, 0xf1 ] LookupLow = [ 0x00, 0x21, 0x42, 0x63, 0x84, 0xa5, 0xc6, 0xe7, 0x08, 0x29, 0x4a, 0x6b, 0x8c, 0xad, 0xce, 0xef ] def __init__(self): self.high = BYTEMASK self.low = BYTEMASK def Update4Bits(self, val): # Step one, extract the Most significant 4 bits of the CRC register #print "val is %d" % (val) t = self.high>>4 #print "t is %d" % (t) # XOR in the Message Data into the extracted bits t = t^val #print "t is %d" % (t) # Shift the CRC Register left 4 bits self.high = (self.high << 4)|(self.low>>4) self.high = self.high & BYTEMASK # force char self.low = self.low <<4 self.low = self.low & BYTEMASK # force char # Do the table lookups and XOR the result into the CRC tables #print "t for lookup is %d" % (t) self.high = self.high ^ self.LookupHigh[t] self.high = self.high & BYTEMASK # force char self.low = self.low ^ self.LookupLow[t] self.low = self.low & BYTEMASK # force char #print "high is %d Low is %d" % (self.high, self.low) def CRC16_Update(self, val): self.Update4Bits(val>>4) # High nibble first self.Update4Bits(val & 0x0f) # Low nibble def run(self, message): """Calculates a CRC""" for c in message: #print c self.CRC16_Update(c) #print "CRC is Low %d High %d" % (self.low, self.high) return [self.low, self.high] # TODO is this next comment a dead comment? # Always read whole DCB # TODO check master address is in legal range def hmFormMsg(destination, protocol, source, function, start, payload) : """Forms a message payload, excluding CRC""" if protocol == HMV3_ID: start_low = (start & BYTEMASK) start_high = (start >> 8) & BYTEMASK if function == FUNC_READ: payloadLength = 0 length_low = (RW_LENGTH_ALL & BYTEMASK) length_high = (RW_LENGTH_ALL >> 8) & BYTEMASK else: payloadLength = len(payload) length_low = (payloadLength & BYTEMASK) length_high = (payloadLength >> 8) & BYTEMASK msg = [destination, 10+payloadLength, source, function, start_low, start_high, length_low, length_high] if function == FUNC_WRITE: msg = msg + payload return msg else: assert 0, "Un-supported protocol found %s" % protocol def hmFormMsgCRC(destination, protocol, source, function, start, payload) : """Forms a message payload, including CRC""" data = hmFormMsg(destination, protocol, source, function, start, payload) crc = crc16() data = data + crc.run(data) return data # expectedLength only used for read msgs as always 7 for write def hmVerifyMsgCRCOK(destination, protocol, source, expectedFunction, expectedLength, datal) : """Verifies message appears legal""" localtime = "<UNKNOWN TIME>" # TODO loop = 2 # TODO badresponse = 0 print datal if protocol == HMV3_ID: checksum = datal[len(datal)-2:] rxmsg = datal[:len(datal)-2] # print checksum print rxmsg crc = crc16() # Initialises the CRC expectedchecksum = crc.run(rxmsg) if expectedchecksum == checksum: print "CRC is correct" else: print "CRC is INCORRECT" s = "%s : Controller %s : Incorrect CRC: %s %s \n" % (localtime, loop, datal, expectedchecksum) sys.stderr.write(s) badresponse += 1 # Check the response dest_addr = datal[0] frame_len_l = datal[1] frame_len_h = datal[2] frame_len = (frame_len_h << 8) | frame_len_l source_addr = datal[3] func_code = datal[4] if (dest_addr != 129 and dest_addr != 160): print "dest_addr is ILLEGAL" s = "%s : Controller %s : Illegal Dest Addr: %s\n" % (localtime, loop, dest_addr) sys.stderr.write(s) badresponse += 1 if (dest_addr != destination): print "dest_addr is INCORRECT" s = "%s : Controller %s : Incorrect Dest Addr: %s\n" % (localtime, loop, dest_addr) sys.stderr.write(s) badresponse += 1 if (source_addr < 1 or source_addr > 32): print "source_addr is ILLEGAL" s = "%s : Controller %s : Illegal Src Addr: %s\n" % (localtime, loop, source_addr) sys.stderr.write(s) badresponse += 1 if (source_addr != source): print "source addr is INCORRECT" s = "%s : Controller %s : Incorrect Src Addr: %s\n" % (localtime, loop, source_addr) sys.stderr.write(s) badresponse += 1 if (func_code != FUNC_WRITE and func_code != FUNC_READ): print "Func Code is UNKNWON" s = "%s : Controller %s : Unknown Func Code: %s\n" % (localtime, loop, func_code) sys.stderr.write(s) badresponse += 1 if (func_code != expectedFunction): print "Func Code is UNEXPECTED" s = "%s : Controller %s : Unexpected Func Code: %s\n" % (localtime, loop, func_code) sys.stderr.write(s) badresponse += 1 if (func_code == FUNC_WRITE and frame_len != 7): # Reply to Write is always 7 long print "response length is INCORRECT" s = "%s : Controller %s : Incorrect length: %s\n" % (localtime, loop, frame_len) sys.stderr.write(s) badresponse += 1 if (len(datal) != frame_len): print "response length MISMATCHES header" s = "%s : Controller %s : Mismatch length: %s %s\n" % (localtime, loop, len(datal), frame_len) sys.stderr.write(s) badresponse += 1 if (func_code == FUNC_READ and expectedLength !=len(datal) ): # Read response length is wrong print "response length not EXPECTED value" s = "%s : Controller %s : Incorrect length: %s\n" % (localtime, loop, frame_len) sys.stderr.write(s) badresponse += 1 if (badresponse == 0): return True else: return False else: assert 0, "Un-supported protocol found %s" % protocol def hmKeyLock_On(controller, serport) : hmKeyLock(controller, KEY_LOCK_LOCK, serport) def hmKeyLock_Off(controller, serport) : hmKeyLock(controller, KEY_LOCK_UNLOCK, serport) def hmKeyLock(controller, state, serport) : """bla bla""" protocol = controller[SL_CONTR_TYPE] if protocol == HMV3_ID: payload = [state] msg = hmFormMsgCRC(controller[SL_ADDR], protocol, MY_MASTER_ADDR, FUNC_WRITE, KEY_LOCK_ADDR, payload) else: "Un-supported protocol found %s" % protocol assert 0, "Un-supported protocol found %s" % protocol # TODO return error/exception print msg string = ''.join(map(chr,msg)) #TODO Need a send msg method try: written = serport.write(string) # Write a string except serial.SerialTimeoutException, e: s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = [] datal = datal + (map(ord,byteread)) if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, controller[SL_ADDR], FUNC_WRITE, DONT_CARE_LENGTH, datal) == False): print "OH DEAR BAD RESPONSE" return 1 def hmSetHolEnd(controller, enddatetime, serport) : """bla bla""" nowdatetime = datetime.now() print nowdatetime if enddatetime < nowdatetime: print "oh dear" # TODO duration = enddatetime - nowdatetime days = duration.days seconds = duration.seconds hours = seconds/(60*60) totalhours = days*24 + hours + 1 print "Setting holiday to end in %d days %d hours or %d total_hours on %s, it is now %s" % (days, hours, totalhours, enddatetime, nowdatetime) hmSetHolHours(controller, totalhours, serport) def hmSetHolHours(controller, hours, serport) : """bla bla""" protocol = controller[SL_CONTR_TYPE] if protocol == HMV3_ID: hours_lo = (hours & BYTEMASK) hours_hi = (hours >> 8) & BYTEMASK payload = [hours_lo, hours_hi] msg = hmFormMsgCRC(controller[SL_ADDR], protocol, MY_MASTER_ADDR, FUNC_WRITE, HOL_HOURS_LO_ADDR, payload) else: "Un-supported protocol found %s" % protocol assert 0, "Un-supported protocol found %s" % protocol # TODO return error/exception print msg string = ''.join(map(chr,msg)) #TODO Need a send msg method try: written = serport.write(string) # Write a string except serial.SerialTimeoutException, e: # TODO local time not defined? s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = [] datal = datal + (map(ord,byteread)) if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, controller[SL_ADDR], FUNC_WRITE, DONT_CARE_LENGTH, datal) == False): print "OH DEAR BAD RESPONSE" return 1 def hmUpdateTime(controller, serport) : """bla bla""" protocol = controller[SL_CONTR_TYPE] if protocol == HMV3_ID: msgtime = time.time() msgtimet = time.localtime(msgtime) day = int(time.strftime("%w", msgtimet)) if (day == 0): day = 7 # Convert python day format to Heatmiser format hour = int(time.strftime("%H", msgtimet)) mins = int(time.strftime("%M", msgtimet)) secs = int(time.strftime("%S", msgtimet)) if (secs == 61): secs = 60 # Need to do this as pyhton seconds can be [0,61] print "%d %d:%d:%d" % (day, hour, mins, secs) payload = [day, hour, mins, secs] msg = hmFormMsgCRC(controller[SL_ADDR], protocol, MY_MASTER_ADDR, FUNC_WRITE, CUR_TIME_ADDR, payload) else: "Un-supported protocol found %s" % protocol assert 0, "Un-supported protocol found %s" % protocol # TODO return error/exception #print msg # http://stackoverflow.com/questions/180606/how-do-i-convert-a-list-of-ascii-values-to-a-string-in-python string = ''.join(map(chr,msg)) #TODO Need a send msg method try: written = serport.write(string) # Write a string except serial.SerialTimeoutException, e: s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = [] datal = datal + (map(ord,byteread)) if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, controller[SL_ADDR], FUNC_WRITE, DONT_CARE_LENGTH, datal) == False): print "OH DEAR BAD RESPONSE" return 1 return 0 def hmSetTemp(controller, temp, serport) : """bla bla""" protocol = controller[SL_CONTR_TYPE] if protocol == HMV3_ID: payload = [temp] msg = hmFormMsgCRC(controller[SL_ADDR], protocol, MY_MASTER_ADDR, FUNC_WRITE, SET_TEMP_ADDR, payload) else: "Un-supported protocol found %s" % protocol assert 0, "Un-supported protocol found %s" % protocol # TODO return error/exception print msg string = ''.join(map(chr,msg)) #TODO Need a send msg method try: written = serport.write(string) # Write a string except serial.SerialTimeoutException, e: s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = [] datal = datal + (map(ord,byteread)) if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, controller[SL_ADDR], FUNC_WRITE, DONT_CARE_LENGTH, datal) == False): print "OH DEAR BAD RESPONSE" return 1 def hmHoldTemp(controller, temp, minutes, serport) : """bla bla""" # @todo reject if number too big hmSetTemp(controller, temp, serport) time.sleep(2) # sleep for 2 seconds before next controller protocol = controller[SL_CONTR_TYPE] if protocol == HMV3_ID: minutes_lo = (minutes & BYTEMASK) minutes_hi = (minutes >> 8) & BYTEMASK payload = [minutes_lo, minutes_hi] # TODO address - is this different for a read? think so , so how do constant msg = hmFormMsgCRC(controller[SL_ADDR], protocol, MY_MASTER_ADDR, FUNC_WRITE, 32, payload) else: "Un-supported protocol found %s" % protocol assert 0, "Un-supported protocol found %s" % protocol # TODO return error/exception print msg string = ''.join(map(chr,msg)) #TODO Need a send msg method try: written = serport.write(string) # Write a string except serial.SerialTimeoutException, e: s= "%s : Write timeout error: %s\n" % (localtime, e) sys.stderr.write(s) # Now wait for reply byteread = serport.read(100) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = [] datal = datal + (map(ord,byteread)) if (hmVerifyMsgCRCOK(MY_MASTER_ADDR, protocol, controller[SL_ADDR], FUNC_WRITE, DONT_CARE_LENGTH, datal) == False): print "OH DEAR BAD RESPONSE" return 1
Python
#!/usr/bin/env python # trigger on heating info or cmd messages # # for each heating event capture event / info message states # need to cater for all elements in the stat_defn # read the t-stats list # setup triggers for info,event and cmd bsc messages # info request messages can simply return the current temp status # cmd messages needs to kick off a temp change # info and event messages (driven from the polling process) needs to maintain a copy of the current temp etc. # xAPBSC.cmd, xAPBSC.query import sys sys.path.append('../xap') from xaplib import Xap import syslog import re # example # { # source=UKUSA.xAPFlash.joggler # target=shawpad.rpi.heating:breakfastbar.temp # } # request # { # } triggerQuery = ["source=shawpad.rpi.heating", "class=xAPBSC"] # query - using info for testing trgcntQ = len(triggerQuery) triggerCmd = ["source=shawpad.rpi.heating", "class=xAPBSC.cmd"] trgcntC = len(triggerCmd) #syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_SYSLOG) def servicexAPStack(xap): if 0: print "<<<<Service xap messages...>>>>\n" def monitorHeating(xap): message, address = xap.receive() # check for Query Message if len(filter(lambda xap: message.find(xap) != -1, triggerQuery)) == trgcntQ: # print message # 1 - check the target for wildcard or specific stat request # 2 - extract the instance (from the between : and .) # 3 - extract the source to create returntarget # 4 - use the instance to identify the last temp value lines = re.split("\n+", message) returntarget = filter(lambda m: "source=" in m,lines) print returntarget newsources = filter(lambda m: "target=" in m,lines) #print elements #xap.SendQueryMsg(returntarget,msg) # check for cmd Message elif len(filter(lambda xap: message.find(xap) != -1, triggerCmd)) == trgcntC: # check the source for wildcard or specific stat request print message # MAIN #syslog.syslog(syslog.LOG_INFO, 'Processing started') #Xap("FF000F01","shawpad.rpi.heating.event").run(monitorHeating)
Python
#!/usr/bin/env python # # XAP support library # # brett@dbzoo.com # # Updated for flubber # ian@shawpad.com import socket, traceback, time class Xap: def __init__(self, uid, source): self.heartbeat_tick = 0; self.uid = uid self.source = source self.sourceInstance = "" self.port = 0 self.running = 1 def run(self, func): self.connect() while self.running: if self.port: self.heartbeat(60) # add receive buffer check here try: func(self) # loop checking receive buffer and heartbeat while waiting for next time to run func except KeyboardInterrupt: self.done() pass except socket.timeout: pass except: traceback.print_exc() self.done() def done(self): self.gout.close() self.gin.close() self.running = 0 def connect(self): host = '' self.gin = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.gin.settimeout(60) try: self.gin.bind((host, 3639)) except socket.error, msg: print "Broadcast socket port 3639 in use" print "Assuming a hub is active" host = '127.0.0.1' for self.port in range(3639,4639): try: self.gin.bind((host, self.port)) except socket.error, msg: print "Socket port %s in use" % self.port continue print "Discovered port %s" % self.port break self.gout = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.gout.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) def send(self ,msg): try: # print "msg:", " port:",self.port self.gout.sendto(msg, ('<broadcast>', 3639)) except: syslog.syslog(syslog.LOG_ERR, 'Error while sending network packet') def sendMsg(self, clazz, target, msg, sourceInstance): if len(target)>0: targetm = "\ntarget=%s" % target else: targetm = "" msg = "xap-header\n{\nv=12\nhop=1\nuid=%s\nclass=%s\nsource=%s%s%s\n}\n%s" % (self.uid, clazz, self.source, sourceInstance, targetm, msg) #print(msg) self.send(msg) def sendLCDMsg(self, msg): msg = "output.state.1\n{\nid=*\ntext=%s\n}" % msg self.sendMsg("xAPBSC.cmd","dbzoo.livebox.Controller:lcd", msg) def sendSMS(self, num, msg): msg = "outbound\n{\nnum=%s\nmsg=%s\n}" % (num, msg) self.sendMsg("sms.message","dbzoo.livebox.sms", msg) def sendInfoMsg(self, msg): self.sendMsg("xAPBSC.info", "", msg) def sendEventMsg(self, msg): self.sendMsg("xAPBSC.event", "", msg) def sendCmdMsg(self, target, msg): self.sendMsg("xAPBSC.cmd", target, msg) def sendQueryMsg(self, target, msg): self.sendMsg("xAPBSC.query", target, msg) def sendInstanceInfoMsg(self, msg, sourceInstance): if len(sourceInstance)>0: sourceInstance = ":%s" % sourceInstance self.sendMsg("xAPBSC.info", "", msg, sourceInstance) def sendInstanceEventMsg(self, msg, sourceInstance): if len(sourceInstance)>0: sourceInstance = ":%s" % sourceInstance self.sendMsg("xAPBSC.event", "", msg, sourceInstance) def receive(self): try: return self.gin.recvfrom(8192) except KeyboardInterrupt: self.done() pass # The HUB won't relay messages to us until it see's our heartbeat knows our listening port. # This must be periodically sent to keep it active on the HUB. def heartbeat(self, interval): now = time.time() if now - self.heartbeat_tick > interval or self.heartbeat_tick == 0: self.heartbeat_tick = now msg="""xap-hbeat { v=12 hop=1 uid=%s class=xap-hbeat-alive source=%s interval=%s port=%s }""" self.send(msg % ("%s%s" % (self.uid[:6],"00"), self.source, interval, self.port))
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl except: from cgi import parse_qsl import oauth2 as oauth REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' consumer_key = None consumer_secret = None if consumer_key is None or consumer_secret is None: print 'You need to edit this script and provide values for the' print 'consumer_key and also consumer_secret.' print '' print 'The values you need come from Twitter - you need to register' print 'as a developer your "application". This is needed only until' print 'Twitter finishes the idea they have of a way to allow open-source' print 'based libraries to have a token that can be used to generate a' print 'one-time use key that will allow the library to make the request' print 'on your behalf.' print '' sys.exit(1) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) print 'Requesting temp token from Twitter' resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': print 'Invalid respond from Twitter requesting temp token: %s' % resp['status'] else: request_token = dict(parse_qsl(content)) print '' print 'Please visit this Twitter page and retrieve the pincode to be used' print 'in the next step to obtaining an Authentication Token:' print '' print '%s?oauth_token=%s' % (AUTHORIZATION_URL, request_token['oauth_token']) print '' pincode = raw_input('Pincode? ') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(pincode) print '' print 'Generating and signing request for an access token' print '' oauth_client = oauth.Client(oauth_consumer, token) resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % pincode) access_token = dict(parse_qsl(content)) if resp['status'] != '200': print 'The request for a Token did not succeed: %s' % resp['status'] print access_token else: print 'Your Twitter Access Token key: %s' % access_token['oauth_token'] print ' Access Token secret: %s' % access_token['oauth_token_secret'] print ''
Python
#!/usr/bin/python2.4 # -*- coding: utf-8 -*-# # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''Unit tests for the twitter.py library''' __author__ = 'python-twitter@googlegroups.com' import os import simplejson import time import calendar import unittest import urllib import twitter class StatusTest(unittest.TestCase): SAMPLE_JSON = '''{"created_at": "Fri Jan 26 23:17:14 +0000 2007", "id": 4391023, "text": "A l\u00e9gp\u00e1rn\u00e1s haj\u00f3m tele van angoln\u00e1kkal.", "user": {"description": "Canvas. JC Penny. Three ninety-eight.", "id": 718443, "location": "Okinawa, Japan", "name": "Kesuke Miyagi", "profile_image_url": "https://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "https://twitter.com/kesuke"}}''' def _GetSampleUser(self): return twitter.User(id=718443, name='Kesuke Miyagi', screen_name='kesuke', description=u'Canvas. JC Penny. Three ninety-eight.', location='Okinawa, Japan', url='https://twitter.com/kesuke', profile_image_url='https://twitter.com/system/user/pro' 'file_image/718443/normal/kesuke.pn' 'g') def _GetSampleStatus(self): return twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A légpárnás hajóm tele van angolnákkal.', user=self._GetSampleUser()) def testInit(self): '''Test the twitter.Status constructor''' status = twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A légpárnás hajóm tele van angolnákkal.', user=self._GetSampleUser()) def testGettersAndSetters(self): '''Test all of the twitter.Status getters and setters''' status = twitter.Status() status.SetId(4391023) self.assertEqual(4391023, status.GetId()) created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1)) status.SetCreatedAt('Fri Jan 26 23:17:14 +0000 2007') self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.GetCreatedAt()) self.assertEqual(created_at, status.GetCreatedAtInSeconds()) status.SetNow(created_at + 10) self.assertEqual("about 10 seconds ago", status.GetRelativeCreatedAt()) status.SetText(u'A légpárnás hajóm tele van angolnákkal.') self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', status.GetText()) status.SetUser(self._GetSampleUser()) self.assertEqual(718443, status.GetUser().id) def testProperties(self): '''Test all of the twitter.Status properties''' status = twitter.Status() status.id = 1 self.assertEqual(1, status.id) created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1)) status.created_at = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.created_at) self.assertEqual(created_at, status.created_at_in_seconds) status.now = created_at + 10 self.assertEqual('about 10 seconds ago', status.relative_created_at) status.user = self._GetSampleUser() self.assertEqual(718443, status.user.id) def _ParseDate(self, string): return calendar.timegm(time.strptime(string, '%b %d %H:%M:%S %Y')) def testRelativeCreatedAt(self): '''Test various permutations of Status relative_created_at''' status = twitter.Status(created_at='Fri Jan 01 12:00:00 +0000 2007') status.now = self._ParseDate('Jan 01 12:00:00 2007') self.assertEqual('about a second ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:01 2007') self.assertEqual('about a second ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:02 2007') self.assertEqual('about 2 seconds ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:05 2007') self.assertEqual('about 5 seconds ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:50 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:01:00 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:01:10 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:02:00 2007') self.assertEqual('about 2 minutes ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:31:50 2007') self.assertEqual('about 31 minutes ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:50:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 13:00:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 13:10:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 14:00:00 2007') self.assertEqual('about 2 hours ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 19:00:00 2007') self.assertEqual('about 7 hours ago', status.relative_created_at) status.now = self._ParseDate('Jan 02 11:30:00 2007') self.assertEqual('about a day ago', status.relative_created_at) status.now = self._ParseDate('Jan 04 12:00:00 2007') self.assertEqual('about 3 days ago', status.relative_created_at) status.now = self._ParseDate('Feb 04 12:00:00 2007') self.assertEqual('about 34 days ago', status.relative_created_at) def testAsJsonString(self): '''Test the twitter.Status AsJsonString method''' self.assertEqual(StatusTest.SAMPLE_JSON, self._GetSampleStatus().AsJsonString()) def testAsDict(self): '''Test the twitter.Status AsDict method''' status = self._GetSampleStatus() data = status.AsDict() self.assertEqual(4391023, data['id']) self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', data['created_at']) self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', data['text']) self.assertEqual(718443, data['user']['id']) def testEq(self): '''Test the twitter.Status __eq__ method''' status = twitter.Status() status.created_at = 'Fri Jan 26 23:17:14 +0000 2007' status.id = 4391023 status.text = u'A légpárnás hajóm tele van angolnákkal.' status.user = self._GetSampleUser() self.assertEqual(status, self._GetSampleStatus()) def testNewFromJsonDict(self): '''Test the twitter.Status NewFromJsonDict method''' data = simplejson.loads(StatusTest.SAMPLE_JSON) status = twitter.Status.NewFromJsonDict(data) self.assertEqual(self._GetSampleStatus(), status) class UserTest(unittest.TestCase): SAMPLE_JSON = '''{"description": "Indeterminate things", "id": 673483, "location": "San Francisco, CA", "name": "DeWitt", "profile_image_url": "https://twitter.com/system/user/profile_image/673483/normal/me.jpg", "screen_name": "dewitt", "status": {"created_at": "Fri Jan 26 17:28:19 +0000 2007", "id": 4212713, "text": "\\"Select all\\" and archive your Gmail inbox. The page loads so much faster!"}, "url": "http://unto.net/"}''' def _GetSampleStatus(self): return twitter.Status(created_at='Fri Jan 26 17:28:19 +0000 2007', id=4212713, text='"Select all" and archive your Gmail inbox. ' ' The page loads so much faster!') def _GetSampleUser(self): return twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', location='San Francisco, CA', url='http://unto.net/', profile_image_url='https://twitter.com/system/user/prof' 'ile_image/673483/normal/me.jpg', status=self._GetSampleStatus()) def testInit(self): '''Test the twitter.User constructor''' user = twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', url='https://twitter.com/dewitt', profile_image_url='https://twitter.com/system/user/prof' 'ile_image/673483/normal/me.jpg', status=self._GetSampleStatus()) def testGettersAndSetters(self): '''Test all of the twitter.User getters and setters''' user = twitter.User() user.SetId(673483) self.assertEqual(673483, user.GetId()) user.SetName('DeWitt') self.assertEqual('DeWitt', user.GetName()) user.SetScreenName('dewitt') self.assertEqual('dewitt', user.GetScreenName()) user.SetDescription('Indeterminate things') self.assertEqual('Indeterminate things', user.GetDescription()) user.SetLocation('San Francisco, CA') self.assertEqual('San Francisco, CA', user.GetLocation()) user.SetProfileImageUrl('https://twitter.com/system/user/profile_im' 'age/673483/normal/me.jpg') self.assertEqual('https://twitter.com/system/user/profile_image/673' '483/normal/me.jpg', user.GetProfileImageUrl()) user.SetStatus(self._GetSampleStatus()) self.assertEqual(4212713, user.GetStatus().id) def testProperties(self): '''Test all of the twitter.User properties''' user = twitter.User() user.id = 673483 self.assertEqual(673483, user.id) user.name = 'DeWitt' self.assertEqual('DeWitt', user.name) user.screen_name = 'dewitt' self.assertEqual('dewitt', user.screen_name) user.description = 'Indeterminate things' self.assertEqual('Indeterminate things', user.description) user.location = 'San Francisco, CA' self.assertEqual('San Francisco, CA', user.location) user.profile_image_url = 'https://twitter.com/system/user/profile_i' \ 'mage/673483/normal/me.jpg' self.assertEqual('https://twitter.com/system/user/profile_image/6734' '83/normal/me.jpg', user.profile_image_url) self.status = self._GetSampleStatus() self.assertEqual(4212713, self.status.id) def testAsJsonString(self): '''Test the twitter.User AsJsonString method''' self.assertEqual(UserTest.SAMPLE_JSON, self._GetSampleUser().AsJsonString()) def testAsDict(self): '''Test the twitter.User AsDict method''' user = self._GetSampleUser() data = user.AsDict() self.assertEqual(673483, data['id']) self.assertEqual('DeWitt', data['name']) self.assertEqual('dewitt', data['screen_name']) self.assertEqual('Indeterminate things', data['description']) self.assertEqual('San Francisco, CA', data['location']) self.assertEqual('https://twitter.com/system/user/profile_image/6734' '83/normal/me.jpg', data['profile_image_url']) self.assertEqual('http://unto.net/', data['url']) self.assertEqual(4212713, data['status']['id']) def testEq(self): '''Test the twitter.User __eq__ method''' user = twitter.User() user.id = 673483 user.name = 'DeWitt' user.screen_name = 'dewitt' user.description = 'Indeterminate things' user.location = 'San Francisco, CA' user.profile_image_url = 'https://twitter.com/system/user/profile_image/67' \ '3483/normal/me.jpg' user.url = 'http://unto.net/' user.status = self._GetSampleStatus() self.assertEqual(user, self._GetSampleUser()) def testNewFromJsonDict(self): '''Test the twitter.User NewFromJsonDict method''' data = simplejson.loads(UserTest.SAMPLE_JSON) user = twitter.User.NewFromJsonDict(data) self.assertEqual(self._GetSampleUser(), user) class TrendTest(unittest.TestCase): SAMPLE_JSON = '''{"name": "Kesuke Miyagi", "query": "Kesuke Miyagi"}''' def _GetSampleTrend(self): return twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007') def testInit(self): '''Test the twitter.Trend constructor''' trend = twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007') def testProperties(self): '''Test all of the twitter.Trend properties''' trend = twitter.Trend() trend.name = 'Kesuke Miyagi' self.assertEqual('Kesuke Miyagi', trend.name) trend.query = 'Kesuke Miyagi' self.assertEqual('Kesuke Miyagi', trend.query) trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', trend.timestamp) def testNewFromJsonDict(self): '''Test the twitter.Trend NewFromJsonDict method''' data = simplejson.loads(TrendTest.SAMPLE_JSON) trend = twitter.Trend.NewFromJsonDict(data, timestamp='Fri Jan 26 23:17:14 +0000 2007') self.assertEqual(self._GetSampleTrend(), trend) def testEq(self): '''Test the twitter.Trend __eq__ method''' trend = twitter.Trend() trend.name = 'Kesuke Miyagi' trend.query = 'Kesuke Miyagi' trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual(trend, self._GetSampleTrend()) class FileCacheTest(unittest.TestCase): def testInit(self): """Test the twitter._FileCache constructor""" cache = twitter._FileCache() self.assert_(cache is not None, 'cache is None') def testSet(self): """Test the twitter._FileCache.Set method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') cache.Remove("foo") def testRemove(self): """Test the twitter._FileCache.Remove method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') cache.Remove("foo") data = cache.Get("foo") self.assertEqual(data, None, 'data is not None') def testGet(self): """Test the twitter._FileCache.Get method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') data = cache.Get("foo") self.assertEqual('Hello World!', data) cache.Remove("foo") def testGetCachedTime(self): """Test the twitter._FileCache.GetCachedTime method""" now = time.time() cache = twitter._FileCache() cache.Set("foo",'Hello World!') cached_time = cache.GetCachedTime("foo") delta = cached_time - now self.assert_(delta <= 1, 'Cached time differs from clock time by more than 1 second.') cache.Remove("foo") class ApiTest(unittest.TestCase): def setUp(self): self._urllib = MockUrllib() api = twitter.Api(consumer_key='CONSUMER_KEY', consumer_secret='CONSUMER_SECRET', access_token_key='OAUTH_TOKEN', access_token_secret='OAUTH_SECRET', cache=None) api.SetUrllib(self._urllib) self._api = api def testTwitterError(self): '''Test that twitter responses containing an error message are wrapped.''' self._AddHandler('https://api.twitter.com/1/statuses/public_timeline.json', curry(self._OpenTestData, 'public_timeline_error.json')) # Manually try/catch so we can check the exception's value try: statuses = self._api.GetPublicTimeline() except twitter.TwitterError, error: # If the error message matches, the test passes self.assertEqual('test error', error.message) else: self.fail('TwitterError expected') def testGetPublicTimeline(self): '''Test the twitter.Api GetPublicTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/public_timeline.json?since_id=12345', curry(self._OpenTestData, 'public_timeline.json')) statuses = self._api.GetPublicTimeline(since_id=12345) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(20, len(statuses)) self.assertEqual(89497702, statuses[0].id) def testGetUserTimeline(self): '''Test the twitter.Api GetUserTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/user_timeline/kesuke.json?count=1', curry(self._OpenTestData, 'user_timeline-kesuke.json')) statuses = self._api.GetUserTimeline('kesuke', count=1) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(89512102, statuses[0].id) self.assertEqual(718443, statuses[0].user.id) def testGetFriendsTimeline(self): '''Test the twitter.Api GetFriendsTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/friends_timeline/kesuke.json', curry(self._OpenTestData, 'friends_timeline-kesuke.json')) statuses = self._api.GetFriendsTimeline('kesuke') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(20, len(statuses)) self.assertEqual(718443, statuses[0].user.id) def testGetStatus(self): '''Test the twitter.Api GetStatus method''' self._AddHandler('https://api.twitter.com/1/statuses/show/89512102.json', curry(self._OpenTestData, 'show-89512102.json')) status = self._api.GetStatus(89512102) self.assertEqual(89512102, status.id) self.assertEqual(718443, status.user.id) def testDestroyStatus(self): '''Test the twitter.Api DestroyStatus method''' self._AddHandler('https://api.twitter.com/1/statuses/destroy/103208352.json', curry(self._OpenTestData, 'status-destroy.json')) status = self._api.DestroyStatus(103208352) self.assertEqual(103208352, status.id) def testPostUpdate(self): '''Test the twitter.Api PostUpdate method''' self._AddHandler('https://api.twitter.com/1/statuses/update.json', curry(self._OpenTestData, 'update.json')) status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) def testGetReplies(self): '''Test the twitter.Api GetReplies method''' self._AddHandler('https://api.twitter.com/1/statuses/replies.json?page=1', curry(self._OpenTestData, 'replies.json')) statuses = self._api.GetReplies(page=1) self.assertEqual(36657062, statuses[0].id) def testGetFriends(self): '''Test the twitter.Api GetFriends method''' self._AddHandler('https://api.twitter.com/1/statuses/friends.json?cursor=123', curry(self._OpenTestData, 'friends.json')) users = self._api.GetFriends(cursor=123) buzz = [u.status for u in users if u.screen_name == 'buzz'] self.assertEqual(89543882, buzz[0].id) def testGetFollowers(self): '''Test the twitter.Api GetFollowers method''' self._AddHandler('https://api.twitter.com/1/statuses/followers.json?page=1', curry(self._OpenTestData, 'followers.json')) users = self._api.GetFollowers(page=1) # This is rather arbitrary, but spot checking is better than nothing alexkingorg = [u.status for u in users if u.screen_name == 'alexkingorg'] self.assertEqual(89554432, alexkingorg[0].id) def testGetFeatured(self): '''Test the twitter.Api GetFeatured method''' self._AddHandler('https://api.twitter.com/1/statuses/featured.json', curry(self._OpenTestData, 'featured.json')) users = self._api.GetFeatured() # This is rather arbitrary, but spot checking is better than nothing stevenwright = [u.status for u in users if u.screen_name == 'stevenwright'] self.assertEqual(86991742, stevenwright[0].id) def testGetDirectMessages(self): '''Test the twitter.Api GetDirectMessages method''' self._AddHandler('https://api.twitter.com/1/direct_messages.json?page=1', curry(self._OpenTestData, 'direct_messages.json')) statuses = self._api.GetDirectMessages(page=1) self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text) def testPostDirectMessage(self): '''Test the twitter.Api PostDirectMessage method''' self._AddHandler('https://api.twitter.com/1/direct_messages/new.json', curry(self._OpenTestData, 'direct_messages-new.json')) status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) def testDestroyDirectMessage(self): '''Test the twitter.Api DestroyDirectMessage method''' self._AddHandler('https://api.twitter.com/1/direct_messages/destroy/3496342.json', curry(self._OpenTestData, 'direct_message-destroy.json')) status = self._api.DestroyDirectMessage(3496342) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, status.sender_id) def testCreateFriendship(self): '''Test the twitter.Api CreateFriendship method''' self._AddHandler('https://api.twitter.com/1/friendships/create/dewitt.json', curry(self._OpenTestData, 'friendship-create.json')) user = self._api.CreateFriendship('dewitt') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, user.id) def testDestroyFriendship(self): '''Test the twitter.Api DestroyFriendship method''' self._AddHandler('https://api.twitter.com/1/friendships/destroy/dewitt.json', curry(self._OpenTestData, 'friendship-destroy.json')) user = self._api.DestroyFriendship('dewitt') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, user.id) def testGetUser(self): '''Test the twitter.Api GetUser method''' self._AddHandler('https://api.twitter.com/1/users/show/dewitt.json', curry(self._OpenTestData, 'show-dewitt.json')) user = self._api.GetUser('dewitt') self.assertEqual('dewitt', user.screen_name) self.assertEqual(89586072, user.status.id) def _AddHandler(self, url, callback): self._urllib.AddHandler(url, callback) def _GetTestDataPath(self, filename): directory = os.path.dirname(os.path.abspath(__file__)) test_data_dir = os.path.join(directory, 'testdata') return os.path.join(test_data_dir, filename) def _OpenTestData(self, filename): f = open(self._GetTestDataPath(filename)) # make sure that the returned object contains an .info() method: # headers are set to {} return urllib.addinfo(f, {}) class MockUrllib(object): '''A mock replacement for urllib that hardcodes specific responses.''' def __init__(self): self._handlers = {} self.HTTPBasicAuthHandler = MockHTTPBasicAuthHandler def AddHandler(self, url, callback): self._handlers[url] = callback def build_opener(self, *handlers): return MockOpener(self._handlers) def HTTPHandler(self, *args, **kwargs): return None def HTTPSHandler(self, *args, **kwargs): return None def OpenerDirector(self): return self.build_opener() class MockOpener(object): '''A mock opener for urllib''' def __init__(self, handlers): self._handlers = handlers self._opened = False def open(self, url, data=None): if self._opened: raise Exception('MockOpener already opened.') # Remove parameters from URL - they're only added by oauth and we # don't want to test oauth if '?' in url: # We split using & and filter on the beginning of each key # This is crude but we have to keep the ordering for now (url, qs) = url.split('?') tokens = [token for token in qs.split('&') if not token.startswith('oauth')] if len(tokens) > 0: url = "%s?%s"%(url, '&'.join(tokens)) if url in self._handlers: self._opened = True return self._handlers[url]() else: raise Exception('Unexpected URL %s (Checked: %s)' % (url, self._handlers)) def add_handler(self, *args, **kwargs): pass def close(self): if not self._opened: raise Exception('MockOpener closed before it was opened.') self._opened = False class MockHTTPBasicAuthHandler(object): '''A mock replacement for HTTPBasicAuthHandler''' def add_password(self, realm, uri, user, passwd): # TODO(dewitt): Add verification that the proper args are passed pass class curry: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def __init__(self, fun, *args, **kwargs): self.fun = fun self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): if kwargs and self.kwargs: kw = self.kwargs.copy() kw.update(kwargs) else: kw = kwargs or self.kwargs return self.fun(*(self.pending + args), **kw) def suite(): suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(FileCacheTest)) suite.addTests(unittest.makeSuite(StatusTest)) suite.addTests(unittest.makeSuite(UserTest)) suite.addTests(unittest.makeSuite(ApiTest)) return suite if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python2.4 '''Load the latest update for a Twitter user and leave it in an XHTML fragment''' __author__ = 'dewitt@google.com' import codecs import getopt import sys import twitter TEMPLATE = """ <div class="twitter"> <span class="twitter-user"><a href="http://twitter.com/%s">Twitter</a>: </span> <span class="twitter-text">%s</span> <span class="twitter-relative-created-at"><a href="http://twitter.com/%s/statuses/%s">Posted %s</a></span> </div> """ def Usage(): print 'Usage: %s [options] twitterid' % __file__ print print ' This script fetches a users latest twitter update and stores' print ' the result in a file as an XHTML fragment' print print ' Options:' print ' --help -h : print this help' print ' --output : the output file [default: stdout]' def FetchTwitter(user, output): assert user statuses = twitter.Api().GetUserTimeline(user=user, count=1) s = statuses[0] xhtml = TEMPLATE % (s.user.screen_name, s.text, s.user.screen_name, s.id, s.relative_created_at) if output: Save(xhtml, output) else: print xhtml def Save(xhtml, output): out = codecs.open(output, mode='w', encoding='ascii', errors='xmlcharrefreplace') out.write(xhtml) out.close() def main(): try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output=']) except getopt.GetoptError: Usage() sys.exit(2) try: user = args[0] except: Usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): Usage() sys.exit(2) if o in ("-o", "--output"): output = a FetchTwitter(user, output) if __name__ == "__main__": main()
Python
#!/usr/bin/python2.4 '''Post a message to twitter''' __author__ = 'dewitt@google.com' import ConfigParser import getopt import os import sys import twitter USAGE = '''Usage: tweet [options] message This script posts a message to Twitter. Options: -h --help : print this help --consumer-key : the twitter consumer key --consumer-secret : the twitter consumer secret --access-key : the twitter access token key --access-secret : the twitter access token secret --encoding : the character set encoding used in input strings, e.g. "utf-8". [optional] Documentation: If either of the command line flags are not present, the environment variables TWEETUSERNAME and TWEETPASSWORD will then be checked for your consumer_key or consumer_secret, respectively. If neither the command line flags nor the enviroment variables are present, the .tweetrc file, if it exists, can be used to set the default consumer_key and consumer_secret. The file should contain the following three lines, replacing *consumer_key* with your consumer key, and *consumer_secret* with your consumer secret: A skeletal .tweetrc file: [Tweet] consumer_key: *consumer_key* consumer_secret: *consumer_password* access_key: *access_key* access_secret: *access_password* ''' def PrintUsageAndExit(): print USAGE sys.exit(2) def GetConsumerKeyEnv(): return os.environ.get("TWEETUSERNAME", None) def GetConsumerSecretEnv(): return os.environ.get("TWEETPASSWORD", None) def GetAccessKeyEnv(): return os.environ.get("TWEETACCESSKEY", None) def GetAccessSecretEnv(): return os.environ.get("TWEETACCESSSECRET", None) class TweetRc(object): def __init__(self): self._config = None def GetConsumerKey(self): return self._GetOption('consumer_key') def GetConsumerSecret(self): return self._GetOption('consumer_secret') def GetAccessKey(self): return self._GetOption('access_key') def GetAccessSecret(self): return self._GetOption('access_secret') def _GetOption(self, option): try: return self._GetConfig().get('Tweet', option) except: return None def _GetConfig(self): if not self._config: self._config = ConfigParser.ConfigParser() self._config.read(os.path.expanduser('~/.tweetrc')) return self._config def main(): try: shortflags = 'h' longflags = ['help', 'consumer-key=', 'consumer-secret=', 'access-key=', 'access-secret=', 'encoding='] opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) except getopt.GetoptError: PrintUsageAndExit() consumer_keyflag = None consumer_secretflag = None access_keyflag = None access_secretflag = None encoding = None for o, a in opts: if o in ("-h", "--help"): PrintUsageAndExit() if o in ("--consumer-key"): consumer_keyflag = a if o in ("--consumer-secret"): consumer_secretflag = a if o in ("--access-key"): access_keyflag = a if o in ("--access-secret"): access_secretflag = a if o in ("--encoding"): encoding = a message = ' '.join(args) if not message: PrintUsageAndExit() rc = TweetRc() consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey() consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret() access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey() access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret() if not consumer_key or not consumer_secret or not access_key or not access_secret: PrintUsageAndExit() api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) try: status = api.PostUpdate(message) except UnicodeDecodeError: print "Your message could not be encoded. Perhaps it contains non-ASCII characters? " print "Try explicitly specifying the encoding with the --encoding flag" sys.exit(2) print "%s just posted: %s" % (status.user.name, status.text) if __name__ == "__main__": main()
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''A class that defines the default URL Shortener. TinyURL is provided as the default and as an example. ''' import urllib # Change History # # 2010-05-16 # TinyURL example and the idea for this comes from a bug filed by # acolorado with patch provided by ghills. Class implementation # was done by bear. # # Issue 19 http://code.google.com/p/python-twitter/issues/detail?id=19 # class ShortenURL(object): '''Helper class to make URL Shortener calls if/when required''' def __init__(self, userid=None, password=None): '''Instantiate a new ShortenURL object Args: userid: userid for any required authorization call [optional] password: password for any required authorization call [optional] ''' self.userid = userid self.password = password def Shorten(self, longURL): '''Call TinyURL API and returned shortened URL result Args: longURL: URL string to shorten Returns: The shortened URL as a string Note: longURL is required and no checks are made to ensure completeness ''' result = None f = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % longURL) try: result = f.read() finally: f.close() return result
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''The setup and build script for the python-twitter library.''' __author__ = 'python-twitter@googlegroups.com' __version__ = '0.8.3' # The base package metadata to be used by both distutils and setuptools METADATA = dict( name = "python-twitter", version = __version__, py_modules = ['twitter'], author='The Python-Twitter Developers', author_email='python-twitter@googlegroups.com', description='A python wrapper around the Twitter API', license='Apache License 2.0', url='http://code.google.com/p/python-twitter/', keywords='twitter api', ) # Extra package metadata to be used only if setuptools is installed SETUPTOOLS_METADATA = dict( install_requires = ['setuptools', 'simplejson', 'oauth2'], include_package_data = True, classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet', ], test_suite = 'twitter_test.suite', ) def Read(file): return open(file).read() def BuildLongDescription(): return '\n'.join([Read('README'), Read('CHANGES')]) def Main(): # Build the long_description from the README and CHANGES METADATA['long_description'] = BuildLongDescription() # Use setuptools if available, otherwise fallback and use distutils try: import setuptools METADATA.update(SETUPTOOLS_METADATA) setuptools.setup(**METADATA) except ImportError: import distutils.core distutils.core.setup(**METADATA) if __name__ == '__main__': Main()
Python
"""Implementation of JSONDecoder """ import re import sys import struct from simplejson.scanner import make_scanner try: from simplejson._speedups import scanstring as c_scanstring except ImportError: c_scanstring = None __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _speedups lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: msg = "Invalid control character %r at" % (terminator,) raise ValueError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: # Unicode escape sequence esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise ValueError(errmsg(msg, s, end)) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise ValueError(errmsg(msg, s, end)) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise ValueError(errmsg(msg, s, end)) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = unichr(uni) end = next_end # Append the unescaped character _append(char) return u''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR): pairs = {} # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': return pairs, end + 1 elif nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 while True: key, end = scanstring(s, end, encoding, strict) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) try: nextchar = s[end] if nextchar in _ws: end += 1 nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): """``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. """ self.encoding = encoding self.object_hook = object_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.scan_once = make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end
Python
"""JSON token scanner """ import re try: from simplejson._speedups import make_scanner as c_make_scanner except ImportError: c_make_scanner = None __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration return _scan_once make_scanner = c_make_scanner or py_make_scanner
Python
"""Implementation of JSONEncoder """ import re try: from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii except ImportError: c_encode_basestring_ascii = None try: from simplejson._speedups import make_encoder as c_make_encoder except ImportError: c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # Assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is True, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is True, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is True, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError("%r is not JSON serializable" % (o,)) def encode(self, o): """Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) return ''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError("Out of range float values are not JSON compliant: %r" % (o,)) return text if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys: _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif isinstance(key, (int, long)): key = str(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif _skipkeys: continue else: raise TypeError("key %r is not a string" % (key,)) if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
Python
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> import decimal >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError("%r is not JSON serializable" % (o,)) ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.0.7' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder', ] from decoder import JSONDecoder from encoder import JSONEncoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s)
Python
r"""Using simplejson from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ import simplejson def main(): import sys if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],)) try: obj = simplejson.load(infile) except ValueError, e: raise SystemExit(e) simplejson.dump(obj, outfile, sort_keys=True, indent=4) outfile.write('\n') if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''A library that provides a Python interface to the Twitter API''' __author__ = 'python-twitter@googlegroups.com' __version__ = '0.8.3' import base64 import calendar import datetime import httplib import os import rfc822 import sys import tempfile import textwrap import time import calendar import urllib import urllib2 import urlparse import gzip import StringIO try: # Python >= 2.6 import json as simplejson except ImportError: try: # Python < 2.6 import simplejson except ImportError: try: # Google App Engine from django.utils import simplejson except ImportError: raise ImportError, "Unable to load a json library" # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl, parse_qs except ImportError: from cgi import parse_qsl, parse_qs try: from hashlib import md5 except ImportError: from md5 import md5 import oauth2 as oauth CHARACTER_LIMIT = 140 # A singleton representing a lazily instantiated FileCache. DEFAULT_CACHE = object() REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' class TwitterError(Exception): '''Base class for Twitter errors''' @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class Status(object): '''A class representing the Status structure used by the twitter API. The Status structure exposes the following properties: status.created_at status.created_at_in_seconds # read only status.favorited status.in_reply_to_screen_name status.in_reply_to_user_id status.in_reply_to_status_id status.truncated status.source status.id status.text status.location status.relative_created_at # read only status.user status.urls status.user_mentions status.hashtags status.geo status.place status.coordinates status.contributors ''' def __init__(self, created_at=None, favorited=None, id=None, text=None, location=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None, urls=None, user_mentions=None, hashtags=None, geo=None, place=None, coordinates=None, contributors=None, retweeted=None, retweeted_status=None, retweet_count=None): '''An object to hold a Twitter status message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: created_at: The time this status message was posted. [Optional] favorited: Whether this is a favorite of the authenticated user. [Optional] id: The unique id of this status message. [Optional] text: The text of this status message. [Optional] location: the geolocation string associated with this message. [Optional] relative_created_at: A human readable string representing the posting time. [Optional] user: A twitter.User instance representing the person posting the message. [Optional] now: The current time, if the client choses to set it. Defaults to the wall clock time. [Optional] urls: user_mentions: hashtags: geo: place: coordinates: contributors: retweeted: retweeted_status: retweet_count: ''' self.created_at = created_at self.favorited = favorited self.id = id self.text = text self.location = location self.user = user self.now = now self.in_reply_to_screen_name = in_reply_to_screen_name self.in_reply_to_user_id = in_reply_to_user_id self.in_reply_to_status_id = in_reply_to_status_id self.truncated = truncated self.retweeted = retweeted self.source = source self.urls = urls self.user_mentions = user_mentions self.hashtags = hashtags self.geo = geo self.place = place self.coordinates = coordinates self.contributors = contributors self.retweeted_status = retweeted_status self.retweet_count = retweet_count def GetCreatedAt(self): '''Get the time this status message was posted. Returns: The time this status message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this status message was posted. Args: created_at: The time this status message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this status message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this status message was posted, in seconds since the epoch. Returns: The time this status message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this status message was " "posted, in seconds since the epoch") def GetFavorited(self): '''Get the favorited setting of this status message. Returns: True if this status message is favorited; False otherwise ''' return self._favorited def SetFavorited(self, favorited): '''Set the favorited state of this status message. Args: favorited: boolean True/False favorited state of this status message ''' self._favorited = favorited favorited = property(GetFavorited, SetFavorited, doc='The favorited state of this status message.') def GetId(self): '''Get the unique id of this status message. Returns: The unique id of this status message ''' return self._id def SetId(self, id): '''Set the unique id of this status message. Args: id: The unique id of this status message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this status message.') def GetInReplyToScreenName(self): return self._in_reply_to_screen_name def SetInReplyToScreenName(self, in_reply_to_screen_name): self._in_reply_to_screen_name = in_reply_to_screen_name in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName, doc='') def GetInReplyToUserId(self): return self._in_reply_to_user_id def SetInReplyToUserId(self, in_reply_to_user_id): self._in_reply_to_user_id = in_reply_to_user_id in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId, doc='') def GetInReplyToStatusId(self): return self._in_reply_to_status_id def SetInReplyToStatusId(self, in_reply_to_status_id): self._in_reply_to_status_id = in_reply_to_status_id in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId, doc='') def GetTruncated(self): return self._truncated def SetTruncated(self, truncated): self._truncated = truncated truncated = property(GetTruncated, SetTruncated, doc='') def GetRetweeted(self): return self._retweeted def SetRetweeted(self, retweeted): self._retweeted = retweeted retweeted = property(GetRetweeted, SetRetweeted, doc='') def GetSource(self): return self._source def SetSource(self, source): self._source = source source = property(GetSource, SetSource, doc='') def GetText(self): '''Get the text of this status message. Returns: The text of this status message. ''' return self._text def SetText(self, text): '''Set the text of this status message. Args: text: The text of this status message ''' self._text = text text = property(GetText, SetText, doc='The text of this status message') def GetLocation(self): '''Get the geolocation associated with this status message Returns: The geolocation string of this status message. ''' return self._location def SetLocation(self, location): '''Set the geolocation associated with this status message Args: location: The geolocation string of this status message ''' self._location = location location = property(GetLocation, SetLocation, doc='The geolocation string of this status message') def GetRelativeCreatedAt(self): '''Get a human redable string representing the posting time Returns: A human readable string representing the posting time ''' fudge = 1.25 delta = long(self.now) - long(self.created_at_in_seconds) if delta < (1 * fudge): return 'about a second ago' elif delta < (60 * (1/fudge)): return 'about %d seconds ago' % (delta) elif delta < (60 * fudge): return 'about a minute ago' elif delta < (60 * 60 * (1/fudge)): return 'about %d minutes ago' % (delta / 60) elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1: return 'about an hour ago' elif delta < (60 * 60 * 24 * (1/fudge)): return 'about %d hours ago' % (delta / (60 * 60)) elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1: return 'about a day ago' else: return 'about %d days ago' % (delta / (60 * 60 * 24)) relative_created_at = property(GetRelativeCreatedAt, doc='Get a human readable string representing ' 'the posting time') def GetUser(self): '''Get a twitter.User reprenting the entity posting this status message. Returns: A twitter.User reprenting the entity posting this status message ''' return self._user def SetUser(self, user): '''Set a twitter.User reprenting the entity posting this status message. Args: user: A twitter.User reprenting the entity posting this status message ''' self._user = user user = property(GetUser, SetUser, doc='A twitter.User reprenting the entity posting this ' 'status message') def GetNow(self): '''Get the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Returns: Whatever the status instance believes the current time to be, in seconds since the epoch. ''' if self._now is None: self._now = time.time() return self._now def SetNow(self, now): '''Set the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Args: now: The wallclock time for this instance. ''' self._now = now now = property(GetNow, SetNow, doc='The wallclock time for this status instance.') def GetGeo(self): return self._geo def SetGeo(self, geo): self._geo = geo geo = property(GetGeo, SetGeo, doc='') def GetPlace(self): return self._place def SetPlace(self, place): self._place = place place = property(GetPlace, SetPlace, doc='') def GetCoordinates(self): return self._coordinates def SetCoordinates(self, coordinates): self._coordinates = coordinates coordinates = property(GetCoordinates, SetCoordinates, doc='') def GetContributors(self): return self._contributors def SetContributors(self, contributors): self._contributors = contributors contributors = property(GetContributors, SetContributors, doc='') def GetRetweeted_status(self): return self._retweeted_status def SetRetweeted_status(self, retweeted_status): self._retweeted_status = retweeted_status retweeted_status = property(GetRetweeted_status, SetRetweeted_status, doc='') def GetRetweetCount(self): return self._retweet_count def SetRetweetCount(self, retweet_count): self._retweet_count = retweet_count retweet_count = property(GetRetweetCount, SetRetweetCount, doc='') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.created_at == other.created_at and \ self.id == other.id and \ self.text == other.text and \ self.location == other.location and \ self.user == other.user and \ self.in_reply_to_screen_name == other.in_reply_to_screen_name and \ self.in_reply_to_user_id == other.in_reply_to_user_id and \ self.in_reply_to_status_id == other.in_reply_to_status_id and \ self.truncated == other.truncated and \ self.retweeted == other.retweeted and \ self.favorited == other.favorited and \ self.source == other.source and \ self.geo == other.geo and \ self.place == other.place and \ self.coordinates == other.coordinates and \ self.contributors == other.contributors and \ self.retweeted_status == other.retweeted_status and \ self.retweet_count == other.retweet_count except AttributeError: return False def __str__(self): '''A string representation of this twitter.Status instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.Status instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.Status instance. Returns: A JSON string representation of this twitter.Status instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.Status instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.Status instance ''' data = {} if self.created_at: data['created_at'] = self.created_at if self.favorited: data['favorited'] = self.favorited if self.id: data['id'] = self.id if self.text: data['text'] = self.text if self.location: data['location'] = self.location if self.user: data['user'] = self.user.AsDict() if self.in_reply_to_screen_name: data['in_reply_to_screen_name'] = self.in_reply_to_screen_name if self.in_reply_to_user_id: data['in_reply_to_user_id'] = self.in_reply_to_user_id if self.in_reply_to_status_id: data['in_reply_to_status_id'] = self.in_reply_to_status_id if self.truncated is not None: data['truncated'] = self.truncated if self.retweeted is not None: data['retweeted'] = self.retweeted if self.favorited is not None: data['favorited'] = self.favorited if self.source: data['source'] = self.source if self.geo: data['geo'] = self.geo if self.place: data['place'] = self.place if self.coordinates: data['coordinates'] = self.coordinates if self.contributors: data['contributors'] = self.contributors if self.hashtags: data['hashtags'] = [h.text for h in self.hashtags] if self.retweeted_status: data['retweeted_status'] = self.retweeted_status.AsDict() if self.retweet_count: data['retweet_count'] = self.retweet_count if self.urls: data['urls'] = dict([(url.url, url.expanded_url) for url in self.urls]) if self.user_mentions: data['user_mentions'] = [um.AsDict() for um in self.user_mentions] return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Status instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None if 'retweeted_status' in data: retweeted_status = Status.NewFromJsonDict(data['retweeted_status']) else: retweeted_status = None urls = None user_mentions = None hashtags = None if 'entities' in data: if 'urls' in data['entities']: urls = [Url.NewFromJsonDict(u) for u in data['entities']['urls']] if 'user_mentions' in data['entities']: user_mentions = [User.NewFromJsonDict(u) for u in data['entities']['user_mentions']] if 'hashtags' in data['entities']: hashtags = [Hashtag.NewFromJsonDict(h) for h in data['entities']['hashtags']] return Status(created_at=data.get('created_at', None), favorited=data.get('favorited', None), id=data.get('id', None), text=data.get('text', None), location=data.get('location', None), in_reply_to_screen_name=data.get('in_reply_to_screen_name', None), in_reply_to_user_id=data.get('in_reply_to_user_id', None), in_reply_to_status_id=data.get('in_reply_to_status_id', None), truncated=data.get('truncated', None), retweeted=data.get('retweeted', None), source=data.get('source', None), user=user, urls=urls, user_mentions=user_mentions, hashtags=hashtags, geo=data.get('geo', None), place=data.get('place', None), coordinates=data.get('coordinates', None), contributors=data.get('contributors', None), retweeted_status=retweeted_status, retweet_count=data.get('retweet_count', None)) class User(object): '''A class representing the User structure used by the twitter API. The User structure exposes the following properties: user.id user.name user.screen_name user.location user.description user.profile_image_url user.profile_background_tile user.profile_background_image_url user.profile_sidebar_fill_color user.profile_background_color user.profile_link_color user.profile_text_color user.protected user.utc_offset user.time_zone user.url user.status user.statuses_count user.followers_count user.friends_count user.favourites_count user.geo_enabled user.verified user.lang user.notifications user.contributors_enabled user.created_at user.listed_count ''' def __init__(self, id=None, name=None, screen_name=None, location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, profile_sidebar_fill_color=None, profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, utc_offset=None, time_zone=None, followers_count=None, friends_count=None, statuses_count=None, favourites_count=None, url=None, status=None, geo_enabled=None, verified=None, lang=None, notifications=None, contributors_enabled=None, created_at=None, listed_count=None): self.id = id self.name = name self.screen_name = screen_name self.location = location self.description = description self.profile_image_url = profile_image_url self.profile_background_tile = profile_background_tile self.profile_background_image_url = profile_background_image_url self.profile_sidebar_fill_color = profile_sidebar_fill_color self.profile_background_color = profile_background_color self.profile_link_color = profile_link_color self.profile_text_color = profile_text_color self.protected = protected self.utc_offset = utc_offset self.time_zone = time_zone self.followers_count = followers_count self.friends_count = friends_count self.statuses_count = statuses_count self.favourites_count = favourites_count self.url = url self.status = status self.geo_enabled = geo_enabled self.verified = verified self.lang = lang self.notifications = notifications self.contributors_enabled = contributors_enabled self.created_at = created_at self.listed_count = listed_count def GetId(self): '''Get the unique id of this user. Returns: The unique id of this user ''' return self._id def SetId(self, id): '''Set the unique id of this user. Args: id: The unique id of this user. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this user.') def GetName(self): '''Get the real name of this user. Returns: The real name of this user ''' return self._name def SetName(self, name): '''Set the real name of this user. Args: name: The real name of this user ''' self._name = name name = property(GetName, SetName, doc='The real name of this user.') def GetScreenName(self): '''Get the short twitter name of this user. Returns: The short twitter name of this user ''' return self._screen_name def SetScreenName(self, screen_name): '''Set the short twitter name of this user. Args: screen_name: the short twitter name of this user ''' self._screen_name = screen_name screen_name = property(GetScreenName, SetScreenName, doc='The short twitter name of this user.') def GetLocation(self): '''Get the geographic location of this user. Returns: The geographic location of this user ''' return self._location def SetLocation(self, location): '''Set the geographic location of this user. Args: location: The geographic location of this user ''' self._location = location location = property(GetLocation, SetLocation, doc='The geographic location of this user.') def GetDescription(self): '''Get the short text description of this user. Returns: The short text description of this user ''' return self._description def SetDescription(self, description): '''Set the short text description of this user. Args: description: The short text description of this user ''' self._description = description description = property(GetDescription, SetDescription, doc='The short text description of this user.') def GetUrl(self): '''Get the homepage url of this user. Returns: The homepage url of this user ''' return self._url def SetUrl(self, url): '''Set the homepage url of this user. Args: url: The homepage url of this user ''' self._url = url url = property(GetUrl, SetUrl, doc='The homepage url of this user.') def GetProfileImageUrl(self): '''Get the url of the thumbnail of this user. Returns: The url of the thumbnail of this user ''' return self._profile_image_url def SetProfileImageUrl(self, profile_image_url): '''Set the url of the thumbnail of this user. Args: profile_image_url: The url of the thumbnail of this user ''' self._profile_image_url = profile_image_url profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl, doc='The url of the thumbnail of this user.') def GetProfileBackgroundTile(self): '''Boolean for whether to tile the profile background image. Returns: True if the background is to be tiled, False if not, None if unset. ''' return self._profile_background_tile def SetProfileBackgroundTile(self, profile_background_tile): '''Set the boolean flag for whether to tile the profile background image. Args: profile_background_tile: Boolean flag for whether to tile or not. ''' self._profile_background_tile = profile_background_tile profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile, doc='Boolean for whether to tile the background image.') def GetProfileBackgroundImageUrl(self): return self._profile_background_image_url def SetProfileBackgroundImageUrl(self, profile_background_image_url): self._profile_background_image_url = profile_background_image_url profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl, doc='The url of the profile background of this user.') def GetProfileSidebarFillColor(self): return self._profile_sidebar_fill_color def SetProfileSidebarFillColor(self, profile_sidebar_fill_color): self._profile_sidebar_fill_color = profile_sidebar_fill_color profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor) def GetProfileBackgroundColor(self): return self._profile_background_color def SetProfileBackgroundColor(self, profile_background_color): self._profile_background_color = profile_background_color profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor) def GetProfileLinkColor(self): return self._profile_link_color def SetProfileLinkColor(self, profile_link_color): self._profile_link_color = profile_link_color profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor) def GetProfileTextColor(self): return self._profile_text_color def SetProfileTextColor(self, profile_text_color): self._profile_text_color = profile_text_color profile_text_color = property(GetProfileTextColor, SetProfileTextColor) def GetProtected(self): return self._protected def SetProtected(self, protected): self._protected = protected protected = property(GetProtected, SetProtected) def GetUtcOffset(self): return self._utc_offset def SetUtcOffset(self, utc_offset): self._utc_offset = utc_offset utc_offset = property(GetUtcOffset, SetUtcOffset) def GetTimeZone(self): '''Returns the current time zone string for the user. Returns: The descriptive time zone string for the user. ''' return self._time_zone def SetTimeZone(self, time_zone): '''Sets the user's time zone string. Args: time_zone: The descriptive time zone to assign for the user. ''' self._time_zone = time_zone time_zone = property(GetTimeZone, SetTimeZone) def GetStatus(self): '''Get the latest twitter.Status of this user. Returns: The latest twitter.Status of this user ''' return self._status def SetStatus(self, status): '''Set the latest twitter.Status of this user. Args: status: The latest twitter.Status of this user ''' self._status = status status = property(GetStatus, SetStatus, doc='The latest twitter.Status of this user.') def GetFriendsCount(self): '''Get the friend count for this user. Returns: The number of users this user has befriended. ''' return self._friends_count def SetFriendsCount(self, count): '''Set the friend count for this user. Args: count: The number of users this user has befriended. ''' self._friends_count = count friends_count = property(GetFriendsCount, SetFriendsCount, doc='The number of friends for this user.') def GetListedCount(self): '''Get the listed count for this user. Returns: The number of lists this user belongs to. ''' return self._listed_count def SetListedCount(self, count): '''Set the listed count for this user. Args: count: The number of lists this user belongs to. ''' self._listed_count = count listed_count = property(GetListedCount, SetListedCount, doc='The number of lists this user belongs to.') def GetFollowersCount(self): '''Get the follower count for this user. Returns: The number of users following this user. ''' return self._followers_count def SetFollowersCount(self, count): '''Set the follower count for this user. Args: count: The number of users following this user. ''' self._followers_count = count followers_count = property(GetFollowersCount, SetFollowersCount, doc='The number of users following this user.') def GetStatusesCount(self): '''Get the number of status updates for this user. Returns: The number of status updates for this user. ''' return self._statuses_count def SetStatusesCount(self, count): '''Set the status update count for this user. Args: count: The number of updates for this user. ''' self._statuses_count = count statuses_count = property(GetStatusesCount, SetStatusesCount, doc='The number of updates for this user.') def GetFavouritesCount(self): '''Get the number of favourites for this user. Returns: The number of favourites for this user. ''' return self._favourites_count def SetFavouritesCount(self, count): '''Set the favourite count for this user. Args: count: The number of favourites for this user. ''' self._favourites_count = count favourites_count = property(GetFavouritesCount, SetFavouritesCount, doc='The number of favourites for this user.') def GetGeoEnabled(self): '''Get the setting of geo_enabled for this user. Returns: True/False if Geo tagging is enabled ''' return self._geo_enabled def SetGeoEnabled(self, geo_enabled): '''Set the latest twitter.geo_enabled of this user. Args: geo_enabled: True/False if Geo tagging is to be enabled ''' self._geo_enabled = geo_enabled geo_enabled = property(GetGeoEnabled, SetGeoEnabled, doc='The value of twitter.geo_enabled for this user.') def GetVerified(self): '''Get the setting of verified for this user. Returns: True/False if user is a verified account ''' return self._verified def SetVerified(self, verified): '''Set twitter.verified for this user. Args: verified: True/False if user is a verified account ''' self._verified = verified verified = property(GetVerified, SetVerified, doc='The value of twitter.verified for this user.') def GetLang(self): '''Get the setting of lang for this user. Returns: language code of the user ''' return self._lang def SetLang(self, lang): '''Set twitter.lang for this user. Args: lang: language code for the user ''' self._lang = lang lang = property(GetLang, SetLang, doc='The value of twitter.lang for this user.') def GetNotifications(self): '''Get the setting of notifications for this user. Returns: True/False for the notifications setting of the user ''' return self._notifications def SetNotifications(self, notifications): '''Set twitter.notifications for this user. Args: notifications: True/False notifications setting for the user ''' self._notifications = notifications notifications = property(GetNotifications, SetNotifications, doc='The value of twitter.notifications for this user.') def GetContributorsEnabled(self): '''Get the setting of contributors_enabled for this user. Returns: True/False contributors_enabled of the user ''' return self._contributors_enabled def SetContributorsEnabled(self, contributors_enabled): '''Set twitter.contributors_enabled for this user. Args: contributors_enabled: True/False contributors_enabled setting for the user ''' self._contributors_enabled = contributors_enabled contributors_enabled = property(GetContributorsEnabled, SetContributorsEnabled, doc='The value of twitter.contributors_enabled for this user.') def GetCreatedAt(self): '''Get the setting of created_at for this user. Returns: created_at value of the user ''' return self._created_at def SetCreatedAt(self, created_at): '''Set twitter.created_at for this user. Args: created_at: created_at value for the user ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The value of twitter.created_at for this user.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.screen_name == other.screen_name and \ self.location == other.location and \ self.description == other.description and \ self.profile_image_url == other.profile_image_url and \ self.profile_background_tile == other.profile_background_tile and \ self.profile_background_image_url == other.profile_background_image_url and \ self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \ self.profile_background_color == other.profile_background_color and \ self.profile_link_color == other.profile_link_color and \ self.profile_text_color == other.profile_text_color and \ self.protected == other.protected and \ self.utc_offset == other.utc_offset and \ self.time_zone == other.time_zone and \ self.url == other.url and \ self.statuses_count == other.statuses_count and \ self.followers_count == other.followers_count and \ self.favourites_count == other.favourites_count and \ self.friends_count == other.friends_count and \ self.status == other.status and \ self.geo_enabled == other.geo_enabled and \ self.verified == other.verified and \ self.lang == other.lang and \ self.notifications == other.notifications and \ self.contributors_enabled == other.contributors_enabled and \ self.created_at == other.created_at and \ self.listed_count == other.listed_count except AttributeError: return False def __str__(self): '''A string representation of this twitter.User instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.User instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.User instance. Returns: A JSON string representation of this twitter.User instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.screen_name: data['screen_name'] = self.screen_name if self.location: data['location'] = self.location if self.description: data['description'] = self.description if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.profile_background_tile is not None: data['profile_background_tile'] = self.profile_background_tile if self.profile_background_image_url: data['profile_sidebar_fill_color'] = self.profile_background_image_url if self.profile_background_color: data['profile_background_color'] = self.profile_background_color if self.profile_link_color: data['profile_link_color'] = self.profile_link_color if self.profile_text_color: data['profile_text_color'] = self.profile_text_color if self.protected is not None: data['protected'] = self.protected if self.utc_offset: data['utc_offset'] = self.utc_offset if self.time_zone: data['time_zone'] = self.time_zone if self.url: data['url'] = self.url if self.status: data['status'] = self.status.AsDict() if self.friends_count: data['friends_count'] = self.friends_count if self.followers_count: data['followers_count'] = self.followers_count if self.statuses_count: data['statuses_count'] = self.statuses_count if self.favourites_count: data['favourites_count'] = self.favourites_count if self.geo_enabled: data['geo_enabled'] = self.geo_enabled if self.verified: data['verified'] = self.verified if self.lang: data['lang'] = self.lang if self.notifications: data['notifications'] = self.notifications if self.contributors_enabled: data['contributors_enabled'] = self.contributors_enabled if self.created_at: data['created_at'] = self.created_at if self.listed_count: data['listed_count'] = self.listed_count return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance ''' if 'status' in data: status = Status.NewFromJsonDict(data['status']) else: status = None return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url', None), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status, geo_enabled=data.get('geo_enabled', None), verified=data.get('verified', None), lang=data.get('lang', None), notifications=data.get('notifications', None), contributors_enabled=data.get('contributors_enabled', None), created_at=data.get('created_at', None), listed_count=data.get('listed_count', None)) class List(object): '''A class representing the List structure used by the twitter API. The List structure exposes the following properties: list.id list.name list.slug list.description list.full_name list.mode list.uri list.member_count list.subscriber_count list.following ''' def __init__(self, id=None, name=None, slug=None, description=None, full_name=None, mode=None, uri=None, member_count=None, subscriber_count=None, following=None, user=None): self.id = id self.name = name self.slug = slug self.description = description self.full_name = full_name self.mode = mode self.uri = uri self.member_count = member_count self.subscriber_count = subscriber_count self.following = following self.user = user def GetId(self): '''Get the unique id of this list. Returns: The unique id of this list ''' return self._id def SetId(self, id): '''Set the unique id of this list. Args: id: The unique id of this list. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this list.') def GetName(self): '''Get the real name of this list. Returns: The real name of this list ''' return self._name def SetName(self, name): '''Set the real name of this list. Args: name: The real name of this list ''' self._name = name name = property(GetName, SetName, doc='The real name of this list.') def GetSlug(self): '''Get the slug of this list. Returns: The slug of this list ''' return self._slug def SetSlug(self, slug): '''Set the slug of this list. Args: slug: The slug of this list. ''' self._slug = slug slug = property(GetSlug, SetSlug, doc='The slug of this list.') def GetDescription(self): '''Get the description of this list. Returns: The description of this list ''' return self._description def SetDescription(self, description): '''Set the description of this list. Args: description: The description of this list. ''' self._description = description description = property(GetDescription, SetDescription, doc='The description of this list.') def GetFull_name(self): '''Get the full_name of this list. Returns: The full_name of this list ''' return self._full_name def SetFull_name(self, full_name): '''Set the full_name of this list. Args: full_name: The full_name of this list. ''' self._full_name = full_name full_name = property(GetFull_name, SetFull_name, doc='The full_name of this list.') def GetMode(self): '''Get the mode of this list. Returns: The mode of this list ''' return self._mode def SetMode(self, mode): '''Set the mode of this list. Args: mode: The mode of this list. ''' self._mode = mode mode = property(GetMode, SetMode, doc='The mode of this list.') def GetUri(self): '''Get the uri of this list. Returns: The uri of this list ''' return self._uri def SetUri(self, uri): '''Set the uri of this list. Args: uri: The uri of this list. ''' self._uri = uri uri = property(GetUri, SetUri, doc='The uri of this list.') def GetMember_count(self): '''Get the member_count of this list. Returns: The member_count of this list ''' return self._member_count def SetMember_count(self, member_count): '''Set the member_count of this list. Args: member_count: The member_count of this list. ''' self._member_count = member_count member_count = property(GetMember_count, SetMember_count, doc='The member_count of this list.') def GetSubscriber_count(self): '''Get the subscriber_count of this list. Returns: The subscriber_count of this list ''' return self._subscriber_count def SetSubscriber_count(self, subscriber_count): '''Set the subscriber_count of this list. Args: subscriber_count: The subscriber_count of this list. ''' self._subscriber_count = subscriber_count subscriber_count = property(GetSubscriber_count, SetSubscriber_count, doc='The subscriber_count of this list.') def GetFollowing(self): '''Get the following status of this list. Returns: The following status of this list ''' return self._following def SetFollowing(self, following): '''Set the following status of this list. Args: following: The following of this list. ''' self._following = following following = property(GetFollowing, SetFollowing, doc='The following status of this list.') def GetUser(self): '''Get the user of this list. Returns: The owner of this list ''' return self._user def SetUser(self, user): '''Set the user of this list. Args: user: The owner of this list. ''' self._user = user user = property(GetUser, SetUser, doc='The owner of this list.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.slug == other.slug and \ self.description == other.description and \ self.full_name == other.full_name and \ self.mode == other.mode and \ self.uri == other.uri and \ self.member_count == other.member_count and \ self.subscriber_count == other.subscriber_count and \ self.following == other.following and \ self.user == other.user except AttributeError: return False def __str__(self): '''A string representation of this twitter.List instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.List instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.List instance. Returns: A JSON string representation of this twitter.List instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.List instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.List instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.slug: data['slug'] = self.slug if self.description: data['description'] = self.description if self.full_name: data['full_name'] = self.full_name if self.mode: data['mode'] = self.mode if self.uri: data['uri'] = self.uri if self.member_count is not None: data['member_count'] = self.member_count if self.subscriber_count is not None: data['subscriber_count'] = self.subscriber_count if self.following is not None: data['following'] = self.following if self.user is not None: data['user'] = self.user return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.List instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None return List(id=data.get('id', None), name=data.get('name', None), slug=data.get('slug', None), description=data.get('description', None), full_name=data.get('full_name', None), mode=data.get('mode', None), uri=data.get('uri', None), member_count=data.get('member_count', None), subscriber_count=data.get('subscriber_count', None), following=data.get('following', None), user=user) class DirectMessage(object): '''A class representing the DirectMessage structure used by the twitter API. The DirectMessage structure exposes the following properties: direct_message.id direct_message.created_at direct_message.created_at_in_seconds # read only direct_message.sender_id direct_message.sender_screen_name direct_message.recipient_id direct_message.recipient_screen_name direct_message.text ''' def __init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None): '''An object to hold a Twitter direct message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: id: The unique id of this direct message. [Optional] created_at: The time this direct message was posted. [Optional] sender_id: The id of the twitter user that sent this message. [Optional] sender_screen_name: The name of the twitter user that sent this message. [Optional] recipient_id: The id of the twitter that received this message. [Optional] recipient_screen_name: The name of the twitter that received this message. [Optional] text: The text of this direct message. [Optional] ''' self.id = id self.created_at = created_at self.sender_id = sender_id self.sender_screen_name = sender_screen_name self.recipient_id = recipient_id self.recipient_screen_name = recipient_screen_name self.text = text def GetId(self): '''Get the unique id of this direct message. Returns: The unique id of this direct message ''' return self._id def SetId(self, id): '''Set the unique id of this direct message. Args: id: The unique id of this direct message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this direct message.') def GetCreatedAt(self): '''Get the time this direct message was posted. Returns: The time this direct message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this direct message was posted. Args: created_at: The time this direct message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this direct message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this direct message was posted, in seconds since the epoch. Returns: The time this direct message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this direct message was " "posted, in seconds since the epoch") def GetSenderId(self): '''Get the unique sender id of this direct message. Returns: The unique sender id of this direct message ''' return self._sender_id def SetSenderId(self, sender_id): '''Set the unique sender id of this direct message. Args: sender_id: The unique sender id of this direct message ''' self._sender_id = sender_id sender_id = property(GetSenderId, SetSenderId, doc='The unique sender id of this direct message.') def GetSenderScreenName(self): '''Get the unique sender screen name of this direct message. Returns: The unique sender screen name of this direct message ''' return self._sender_screen_name def SetSenderScreenName(self, sender_screen_name): '''Set the unique sender screen name of this direct message. Args: sender_screen_name: The unique sender screen name of this direct message ''' self._sender_screen_name = sender_screen_name sender_screen_name = property(GetSenderScreenName, SetSenderScreenName, doc='The unique sender screen name of this direct message.') def GetRecipientId(self): '''Get the unique recipient id of this direct message. Returns: The unique recipient id of this direct message ''' return self._recipient_id def SetRecipientId(self, recipient_id): '''Set the unique recipient id of this direct message. Args: recipient_id: The unique recipient id of this direct message ''' self._recipient_id = recipient_id recipient_id = property(GetRecipientId, SetRecipientId, doc='The unique recipient id of this direct message.') def GetRecipientScreenName(self): '''Get the unique recipient screen name of this direct message. Returns: The unique recipient screen name of this direct message ''' return self._recipient_screen_name def SetRecipientScreenName(self, recipient_screen_name): '''Set the unique recipient screen name of this direct message. Args: recipient_screen_name: The unique recipient screen name of this direct message ''' self._recipient_screen_name = recipient_screen_name recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName, doc='The unique recipient screen name of this direct message.') def GetText(self): '''Get the text of this direct message. Returns: The text of this direct message. ''' return self._text def SetText(self, text): '''Set the text of this direct message. Args: text: The text of this direct message ''' self._text = text text = property(GetText, SetText, doc='The text of this direct message') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.created_at == other.created_at and \ self.sender_id == other.sender_id and \ self.sender_screen_name == other.sender_screen_name and \ self.recipient_id == other.recipient_id and \ self.recipient_screen_name == other.recipient_screen_name and \ self.text == other.text except AttributeError: return False def __str__(self): '''A string representation of this twitter.DirectMessage instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.DirectMessage instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.DirectMessage instance. Returns: A JSON string representation of this twitter.DirectMessage instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.DirectMessage instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.DirectMessage instance ''' data = {} if self.id: data['id'] = self.id if self.created_at: data['created_at'] = self.created_at if self.sender_id: data['sender_id'] = self.sender_id if self.sender_screen_name: data['sender_screen_name'] = self.sender_screen_name if self.recipient_id: data['recipient_id'] = self.recipient_id if self.recipient_screen_name: data['recipient_screen_name'] = self.recipient_screen_name if self.text: data['text'] = self.text return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.DirectMessage instance ''' return DirectMessage(created_at=data.get('created_at', None), recipient_id=data.get('recipient_id', None), sender_id=data.get('sender_id', None), text=data.get('text', None), sender_screen_name=data.get('sender_screen_name', None), id=data.get('id', None), recipient_screen_name=data.get('recipient_screen_name', None)) class Hashtag(object): ''' A class represeinting a twitter hashtag ''' def __init__(self, text=None): self.text = text @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Hashtag instance ''' return Hashtag(text = data.get('text', None)) class Trend(object): ''' A class representing a trending topic ''' def __init__(self, name=None, query=None, timestamp=None): self.name = name self.query = query self.timestamp = timestamp def __str__(self): return 'Name: %s\nQuery: %s\nTimestamp: %s\n' % (self.name, self.query, self.timestamp) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.name == other.name and \ self.query == other.query and \ self.timestamp == other.timestamp except AttributeError: return False @staticmethod def NewFromJsonDict(data, timestamp = None): '''Create a new instance based on a JSON dict Args: data: A JSON dict timestamp: Gets set as the timestamp property of the new object Returns: A twitter.Trend object ''' return Trend(name=data.get('name', None), query=data.get('query', None), timestamp=timestamp) class Url(object): '''A class representing an URL contained in a tweet''' def __init__(self, url=None, expanded_url=None): self.url = url self.expanded_url = expanded_url @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Url instance ''' return Url(url=data.get('url', None), expanded_url=data.get('expanded_url', None)) class Api(object): '''A python interface into the Twitter API By default, the Api caches results for 1 minute. Example usage: To create an instance of the twitter.Api class, with no authentication: >>> import twitter >>> api = twitter.Api() To fetch the most recently posted public twitter status messages: >>> statuses = api.GetPublicTimeline() >>> print [s.user.name for s in statuses] [u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #... To fetch a single user's public status messages, where "user" is either a Twitter "short name" or their user id. >>> statuses = api.GetUserTimeline(user) >>> print [s.text for s in statuses] To use authentication, instantiate the twitter.Api class with a consumer key and secret; and the oAuth key and secret: >>> api = twitter.Api(consumer_key='twitter consumer key', consumer_secret='twitter consumer secret', access_token_key='the_key_given', access_token_secret='the_key_secret') To fetch your friends (after being authenticated): >>> users = api.GetFriends() >>> print [u.name for u in users] To post a twitter status message (after being authenticated): >>> status = api.PostUpdate('I love python-twitter!') >>> print status.text I love python-twitter! There are many other methods, including: >>> api.PostUpdates(status) >>> api.PostDirectMessage(user, text) >>> api.GetUser(user) >>> api.GetReplies() >>> api.GetUserTimeline(user) >>> api.GetStatus(id) >>> api.DestroyStatus(id) >>> api.GetFriendsTimeline(user) >>> api.GetFriends(user) >>> api.GetFollowers() >>> api.GetFeatured() >>> api.GetDirectMessages() >>> api.PostDirectMessage(user, text) >>> api.DestroyDirectMessage(id) >>> api.DestroyFriendship(user) >>> api.CreateFriendship(user) >>> api.GetUserByEmail(email) >>> api.VerifyCredentials() ''' DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute _API_REALM = 'Twitter API' def __init__(self, consumer_key=None, consumer_secret=None, access_token_key=None, access_token_secret=None, input_encoding=None, request_headers=None, cache=DEFAULT_CACHE, shortner=None, base_url=None, use_gzip_compression=False, debugHTTP=False): '''Instantiate a new twitter.Api object. Args: consumer_key: Your Twitter user's consumer_key. consumer_secret: Your Twitter user's consumer_secret. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token's secret, also retrieved from the get_access_token.py run. input_encoding: The encoding used to encode input strings. [Optional] request_header: A dictionary of additional HTTP request headers. [Optional] cache: The cache instance to use. Defaults to DEFAULT_CACHE. Use None to disable caching. [Optional] shortner: The shortner instance to use. Defaults to None. See shorten_url.py for an example shortner. [Optional] base_url: The base URL to use to contact the Twitter API. Defaults to https://api.twitter.com. [Optional] use_gzip_compression: Set to True to tell enable gzip compression for any call made to Twitter. Defaults to False. [Optional] debugHTTP: Set to True to enable debug output from urllib2 when performing any HTTP requests. Defaults to False. [Optional] ''' self.SetCache(cache) self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._input_encoding = input_encoding self._use_gzip = use_gzip_compression self._debugHTTP = debugHTTP self._oauth_consumer = None self._shortlink_size = 19 self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() if base_url is None: self.base_url = 'https://api.twitter.com/1' else: self.base_url = base_url if consumer_key is not None and (access_token_key is None or access_token_secret is None): print >> sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.' print >> sys.stderr, 'If your using this library from a command line utility, please' print >> sys.stderr, 'run the the included get_access_token.py tool to generate one.' raise TwitterError('Twitter requires oAuth Access Token for all API access') self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret) def SetCredentials(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None): '''Set the consumer_key and consumer_secret for this instance Args: consumer_key: The consumer_key of the twitter account. consumer_secret: The consumer_secret for the twitter account. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token's secret, also retrieved from the get_access_token.py run. ''' self._consumer_key = consumer_key self._consumer_secret = consumer_secret self._access_token_key = access_token_key self._access_token_secret = access_token_secret self._oauth_consumer = None if consumer_key is not None and consumer_secret is not None and \ access_token_key is not None and access_token_secret is not None: self._signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT() self._signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() self._oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) self._oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) def ClearCredentials(self): '''Clear the any credentials for this instance ''' self._consumer_key = None self._consumer_secret = None self._access_token_key = None self._access_token_secret = None self._oauth_consumer = None def GetPublicTimeline(self, since_id=None, include_rts=None, include_entities=None): '''Fetch the sequence of public twitter.Status message for all users. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] include_rts: If True, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: An sequence of twitter.Status instances, one for each message ''' parameters = {} if since_id: parameters['since_id'] = since_id if include_rts: parameters['include_rts'] = 1 if include_entities: parameters['include_entities'] = 1 url = '%s/statuses/public_timeline.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def FilterPublicTimeline(self, term, since_id=None): '''Filter the public twitter timeline by a given search term on the local machine. Args: term: term to search by. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] Returns: A sequence of twitter.Status instances, one for each message containing the term ''' statuses = self.GetPublicTimeline(since_id) results = [] for s in statuses: if s.text.lower().find(term.lower()) != -1: results.append(s) return results def GetSearch(self, term=None, geocode=None, since_id=None, per_page=15, page=1, lang="en", show_user="true", query_users=False): '''Return twitter search results for a given term. Args: term: term to search by. Optional if you include geocode. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] geocode: geolocation information in the form (latitude, longitude, radius) [Optional] per_page: number of results to return. Default is 15 [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] lang: language for results. Default is English [Optional] show_user: prefixes screen name in status query_users: If set to False, then all users only have screen_name and profile_image_url available. If set to True, all information of users are available, but it uses lots of request quota, one per status. Returns: A sequence of twitter.Status instances, one for each message containing the term ''' # Build request parameters parameters = {} if since_id: parameters['since_id'] = since_id if term is None and geocode is None: return [] if term is not None: parameters['q'] = term if geocode is not None: parameters['geocode'] = ','.join(map(str, geocode)) parameters['show_user'] = show_user parameters['lang'] = lang parameters['rpp'] = per_page parameters['page'] = page # Make and send requests url = 'http://search.twitter.com/search.json' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) results = [] for x in data['results']: temp = Status.NewFromJsonDict(x) if query_users: # Build user object with new request temp.user = self.GetUser(urllib.quote(x['from_user'])) else: temp.user = User(screen_name=x['from_user'], profile_image_url=x['profile_image_url']) results.append(temp) # Return built list of statuses return results # [Status.NewFromJsonDict(x) for x in data['results']] def GetTrendsCurrent(self, exclude=None): '''Get the current top trending topics Args: exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains the twitter. ''' parameters = {} if exclude: parameters['exclude'] = exclude url = '%s/trends/current.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for t in data['trends']: for item in data['trends'][t]: trends.append(Trend.NewFromJsonDict(item, timestamp = t)) return trends def GetTrendsWoeid(self, woeid, exclude=None): '''Return the top 10 trending topics for a specific WOEID, if trending information is available for it. Args: woeid: the Yahoo! Where On Earth ID for a location. exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains a Trend. ''' parameters = {} if exclude: parameters['exclude'] = exclude url = '%s/trends/%s.json' % (self.base_url, woeid) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] timestamp = data[0]['as_of'] for trend in data[0]['trends']: trends.append(Trend.NewFromJsonDict(trend, timestamp = timestamp)) return trends def GetTrendsDaily(self, exclude=None, startdate=None): '''Get the current top trending topics for each hour in a given day Args: startdate: The start date for the report. Should be in the format YYYY-MM-DD. [Optional] exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 24 entries. Each entry contains the twitter. Trend elements that were trending at the corresponding hour of the day. ''' parameters = {} if exclude: parameters['exclude'] = exclude if not startdate: startdate = time.strftime('%Y-%m-%d', time.gmtime()) parameters['date'] = startdate url = '%s/trends/daily.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for i in xrange(24): trends.append(None) for t in data['trends']: idx = int(time.strftime('%H', time.strptime(t, '%Y-%m-%d %H:%M'))) trends[idx] = [Trend.NewFromJsonDict(x, timestamp = t) for x in data['trends'][t]] return trends def GetTrendsWeekly(self, exclude=None, startdate=None): '''Get the top 30 trending topics for each day in a given week. Args: startdate: The start date for the report. Should be in the format YYYY-MM-DD. [Optional] exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with each entry contains the twitter. Trend elements of trending topics for the corrsponding day of the week ''' parameters = {} if exclude: parameters['exclude'] = exclude if not startdate: startdate = time.strftime('%Y-%m-%d', time.gmtime()) parameters['date'] = startdate url = '%s/trends/weekly.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for i in xrange(7): trends.append(None) # use the epochs of the dates as keys for a dictionary times = dict([(calendar.timegm(time.strptime(t, '%Y-%m-%d')),t) for t in data['trends']]) cnt = 0 # create the resulting structure ordered by the epochs of the dates for e in sorted(times.keys()): trends[cnt] = [Trend.NewFromJsonDict(x, timestamp = times[e]) for x in data['trends'][times[e]]] cnt +=1 return trends def GetFriendsTimeline(self, user=None, count=None, page=None, since_id=None, retweets=None, include_entities=None): '''Fetch the sequence of twitter.Status messages for a user's friends The twitter.Api instance must be authenticated if the user is private. Args: user: Specifies the ID or screen name of the user for whom to return the friends_timeline. If not specified then the authenticated user set in the twitter.Api instance will be used. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 100. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] retweets: If True, the timeline will contain native retweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message ''' if not user and not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") url = '%s/statuses/friends_timeline' % self.base_url if user: url = '%s/%s.json' % (url, user) else: url = '%s.json' % url parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") parameters['count'] = count if page is not None: try: parameters['page'] = int(page) except ValueError: raise TwitterError("'page' must be an integer") if since_id: parameters['since_id'] = since_id if retweets: parameters['include_rts'] = True if include_entities: parameters['include_entities'] = True json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetUserTimeline(self, id=None, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, page=None, include_rts=None, include_entities=None): '''Fetch the sequence of public Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: id: Specifies the ID or screen name of the user for whom to return the user_timeline. [Optional] user_id: Specfies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name. [Optional] screen_name: Specfies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) or equal to the specified ID. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 200. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] include_rts: If True, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of Status instances, one for each message up to count ''' parameters = {} if id: url = '%s/statuses/user_timeline/%s.json' % (self.base_url, id) elif user_id: url = '%s/statuses/user_timeline.json?user_id=%d' % (self.base_url, user_id) elif screen_name: url = ('%s/statuses/user_timeline.json?screen_name=%s' % (self.base_url, screen_name)) elif not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") else: url = '%s/statuses/user_timeline.json' % self.base_url if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError("since_id must be an integer") if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if count: try: parameters['count'] = int(count) except: raise TwitterError("count must be an integer") if page: try: parameters['page'] = int(page) except: raise TwitterError("page must be an integer") if include_rts: parameters['include_rts'] = 1 if include_entities: parameters['include_entities'] = 1 json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetStatus(self, id, include_entities=None): '''Returns a single status message. The twitter.Api instance must be authenticated if the status message is private. Args: id: The numeric ID of the status you are trying to retrieve. include_entities: If True, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A twitter.Status instance representing that status message ''' try: if id: long(id) except: raise TwitterError("id must be an long integer") parameters = {} if include_entities: parameters['include_entities'] = 1 url = '%s/statuses/show/%s.json' % (self.base_url, id) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def DestroyStatus(self, id): '''Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and the authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you're trying to destroy. Returns: A twitter.Status instance representing the destroyed status message ''' try: if id: long(id) except: raise TwitterError("id must be an integer") url = '%s/statuses/destroy/%s.json' % (self.base_url, id) json = self._FetchUrl(url, post_data={'id': id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) @classmethod def _calculate_status_length(cls, status, linksize=19): dummy_link_replacement = 'https://-%d-chars%s/' % (linksize, '-'*(linksize - 18)) shortened = ' '.join([x if not (x.startswith('http://') or x.startswith('https://')) else dummy_link_replacement for x in status.split(' ')]) return len(shortened) def PostUpdate(self, status, in_reply_to_status_id=None): '''Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. [Optional] Returns: A twitter.Status instance representing the message posted. ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/statuses/update.json' % self.base_url if isinstance(status, unicode) or self._input_encoding is None: u_status = status else: u_status = unicode(status, self._input_encoding) if self._calculate_status_length(u_status, self._shortlink_size) > CHARACTER_LIMIT: raise TwitterError("Text must be less than or equal to %d characters. " "Consider using PostUpdates." % CHARACTER_LIMIT) data = {'status': status} if in_reply_to_status_id: data['in_reply_to_status_id'] = in_reply_to_status_id json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def PostUpdates(self, status, continuation=None, **kwargs): '''Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appended to all but the last message. Note that Twitter strips trailing '...' strings from messages. Consider using the unicode \u2026 character (horizontal ellipsis) instead. [Defaults to None] **kwargs: See api.PostUpdate for a list of accepted parameters. Returns: A of list twitter.Status instance representing the messages posted. ''' results = list() if continuation is None: continuation = '' line_length = CHARACTER_LIMIT - len(continuation) lines = textwrap.wrap(status, line_length) for line in lines[0:-1]: results.append(self.PostUpdate(line + continuation, **kwargs)) results.append(self.PostUpdate(lines[-1], **kwargs)) return results def GetUserRetweets(self, count=None, since_id=None, max_id=None, include_entities=False): '''Fetch the sequence of retweets made by a single user. The twitter.Api instance must be authenticated. Args: count: The number of status messages to retrieve. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message up to count ''' url = '%s/statuses/retweeted_by_me.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") if count: parameters['count'] = count if since_id: parameters['since_id'] = since_id if include_entities: parameters['include_entities'] = True if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetReplies(self, since=None, since_id=None, page=None): '''Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @twitterID) to the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] since: Returns: A sequence of twitter.Status instances, one for each reply to the user. ''' url = '%s/statuses/replies.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetRetweets(self, statusid): '''Returns up to 100 of the first retweets of the tweet identified by statusid Args: statusid: The ID of the tweet for which retweets should be searched for Returns: A list of twitter.Status instances, which are retweets of statusid ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instsance must be authenticated.") url = '%s/statuses/retweets/%s.json?include_entities=true&include_rts=true' % (self.base_url, statusid) parameters = {} json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(s) for s in data] def GetFriends(self, user=None, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each friend. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] Returns: A sequence of twitter.User instances, one for each friend ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/statuses/friends/%s.json' % (self.base_url, user) else: url = '%s/statuses/friends.json' % self.base_url parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(x) for x in data['users']] def GetFriendIDs(self, user=None, cursor=-1): '''Returns a list of twitter user id's for every person the specified user is following. Args: user: The id or screen_name of the user to retrieve the id list for [Optional] Returns: A list of integers, one for each user id. ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/friends/ids/%s.json' % (self.base_url, user) else: url = '%s/friends/ids.json' % self.base_url parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return data def GetFollowerIDs(self, userid=None, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances, one for each follower ''' url = '%s/followers/ids.json' % self.base_url parameters = {} parameters['cursor'] = cursor if userid: parameters['user_id'] = userid json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return data def GetFollowers(self, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Args: cursor: Specifies the Twitter API Cursor location to start at. [Optional] Note: there are pagination limits. Returns: A sequence of twitter.User instances, one for each follower ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/statuses/followers.json' % self.base_url result = [] while True: parameters = { 'cursor': cursor } json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [User.NewFromJsonDict(x) for x in data['users']] if 'next_cursor' in data: if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']: break else: break return result def GetFeatured(self): '''Fetch the sequence of twitter.User instances featured on twitter.com The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances ''' url = '%s/statuses/featured.json' % self.base_url json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(x) for x in data] def UsersLookup(self, user_id=None, screen_name=None, users=None): '''Fetch extended information for the specified users. Users may be specified either as lists of either user_ids, screen_names, or twitter.User objects. The list of users that are queried is the union of all specified parameters. The twitter.Api instance must be authenticated. Args: user_id: A list of user_ids to retrieve extended information. [Optional] screen_name: A list of screen_names to retrieve extended information. [Optional] users: A list of twitter.User objects to retrieve extended information. [Optional] Returns: A list of twitter.User objects for the requested users ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") if not user_id and not screen_name and not users: raise TwitterError("Specify at least on of user_id, screen_name, or users.") url = '%s/users/lookup.json' % self.base_url parameters = {} uids = list() if user_id: uids.extend(user_id) if users: uids.extend([u.id for u in users]) if len(uids): parameters['user_id'] = ','.join(["%s" % u for u in uids]) if screen_name: parameters['screen_name'] = ','.join(screen_name) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(u) for u in data] def GetUser(self, user): '''Returns a single user. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = '%s/users/show/%s.json' % (self.base_url, user) json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def GetDirectMessages(self, since=None, since_id=None, page=None): '''Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.DirectMessage instances ''' url = '%s/direct_messages.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [DirectMessage.NewFromJsonDict(x) for x in data] def PostDirectMessage(self, user, text): '''Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. Args: user: The ID or screen name of the recipient user. text: The message text to be posted. Must be less than 140 characters. Returns: A twitter.DirectMessage instance representing the message posted ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/direct_messages/new.json' % self.base_url data = {'text': text, 'user': user} json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data) def DestroyDirectMessage(self, id): '''Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the message destroyed ''' url = '%s/direct_messages/destroy/%s.json' % (self.base_url, id) json = self._FetchUrl(url, post_data={'id': id}) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data) def CreateFriendship(self, user): '''Befriends the user specified in the user parameter as the authenticating user. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user to befriend. Returns: A twitter.User instance representing the befriended user. ''' url = '%s/friendships/create/%s.json' % (self.base_url, user) json = self._FetchUrl(url, post_data={'user': user}) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def DestroyFriendship(self, user): '''Discontinues friendship with the user specified in the user parameter. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user with whom to discontinue friendship. Returns: A twitter.User instance representing the discontinued friend. ''' url = '%s/friendships/destroy/%s.json' % (self.base_url, user) json = self._FetchUrl(url, post_data={'user': user}) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def CreateFavorite(self, status): '''Favorites the status specified in the status parameter as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status instance to mark as a favorite. Returns: A twitter.Status instance representing the newly-marked favorite. ''' url = '%s/favorites/create/%s.json' % (self.base_url, status.id) json = self._FetchUrl(url, post_data={'id': status.id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def DestroyFavorite(self, status): '''Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status to unmark as a favorite. Returns: A twitter.Status instance representing the newly-unmarked favorite. ''' url = '%s/favorites/destroy/%s.json' % (self.base_url, status.id) json = self._FetchUrl(url, post_data={'id': status.id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def GetFavorites(self, user=None, page=None): '''Return a list of Status objects representing favorited tweets. By default, returns the (up to) 20 most recent tweets for the authenticated user. Args: user: The twitter name or id of the user whose favorites you are fetching. If not specified, defaults to the authenticated user. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] ''' parameters = {} if page: parameters['page'] = page if user: url = '%s/favorites/%s.json' % (self.base_url, user) elif not user and not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") else: url = '%s/favorites.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetMentions(self, since_id=None, max_id=None, page=None): '''Returns the 20 most recent mentions (status containing @twitterID) for the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) the specified ID. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.Status instances, one for each mention of the user. ''' url = '%s/statuses/mentions.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since_id: parameters['since_id'] = since_id if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def CreateList(self, user, name, mode=None, description=None): '''Creates a new list with the give name The twitter.Api instance must be authenticated. Args: user: Twitter name to create the list for name: New name for the list mode: 'public' or 'private'. Defaults to 'public'. [Optional] description: Description of the list. [Optional] Returns: A twitter.List instance representing the new list ''' url = '%s/%s/lists.json' % (self.base_url, user) parameters = {'name': name} if mode is not None: parameters['mode'] = mode if description is not None: parameters['description'] = description json = self._FetchUrl(url, post_data=parameters) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def DestroyList(self, user, id): '''Destroys the list from the given user The twitter.Api instance must be authenticated. Args: user: The user to remove the list from. id: The slug or id of the list to remove. Returns: A twitter.List instance representing the removed list. ''' url = '%s/%s/lists/%s.json' % (self.base_url, user, id) json = self._FetchUrl(url, post_data={'_method': 'DELETE'}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def CreateSubscription(self, owner, list): '''Creates a subscription to a list by the authenticated user The twitter.Api instance must be authenticated. Args: owner: User name or id of the owner of the list being subscribed to. list: The slug or list id to subscribe the user to Returns: A twitter.List instance representing the list subscribed to ''' url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list) json = self._FetchUrl(url, post_data={'list_id': list}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def DestroySubscription(self, owner, list): '''Destroys the subscription to a list for the authenticated user The twitter.Api instance must be authenticated. Args: owner: The user id or screen name of the user that owns the list that is to be unsubscribed from list: The slug or list id of the list to unsubscribe from Returns: A twitter.List instance representing the removed list. ''' url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list) json = self._FetchUrl(url, post_data={'_method': 'DELETE', 'list_id': list}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def GetSubscriptions(self, user, cursor=-1): '''Fetch the sequence of Lists that the given user is subscribed to The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/%s/lists/subscriptions.json' % (self.base_url, user) parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']] def GetLists(self, user, cursor=-1): '''Fetch the sequence of lists for a user. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user whose friends you are fetching. If the passed in user is the same as the authenticated user then you will also receive private list data. cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/%s/lists.json' % (self.base_url, user) parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']] def GetUserByEmail(self, email): '''Returns a single user by email address. Args: email: The email of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = '%s/users/show.json?email=%s' % (self.base_url, email) json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def VerifyCredentials(self): '''Returns a twitter.User instance if the authenticating user is valid. Returns: A twitter.User instance representing that user if the credentials are valid, None otherwise. ''' if not self._oauth_consumer: raise TwitterError("Api instance must first be given user credentials.") url = '%s/account/verify_credentials.json' % self.base_url try: json = self._FetchUrl(url, no_cache=True) except urllib2.HTTPError, http_error: if http_error.code == httplib.UNAUTHORIZED: return None else: raise http_error data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def SetCache(self, cache): '''Override the default cache. Set to None to prevent caching. Args: cache: An instance that supports the same API as the twitter._FileCache ''' if cache == DEFAULT_CACHE: self._cache = _FileCache() else: self._cache = cache def SetUrllib(self, urllib): '''Override the default urllib implementation. Args: urllib: An instance that supports the same API as the urllib2 module ''' self._urllib = urllib def SetCacheTimeout(self, cache_timeout): '''Override the default cache timeout. Args: cache_timeout: Time, in seconds, that responses should be reused. ''' self._cache_timeout = cache_timeout def SetUserAgent(self, user_agent): '''Override the default user agent Args: user_agent: A string that should be send to the server as the User-agent ''' self._request_headers['User-Agent'] = user_agent def SetXTwitterHeaders(self, client, url, version): '''Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the 'X-Twitter-Client' header. url: The URL of the meta.xml as a string. Will be sent to the server as the 'X-Twitter-Client-URL' header. version: The client version as a string. Will be sent to the server as the 'X-Twitter-Client-Version' header. ''' self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version def SetSource(self, source): '''Suggest the "from source" value to be displayed on the Twitter web site. The value of the 'source' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the server as the 'source' parameter. ''' self._default_params['source'] = source def GetRateLimitStatus(self): '''Fetch the rate limit status for the currently authorized user. Returns: A dictionary containing the time the limit will reset (reset_time), the number of remaining hits allowed before the reset (remaining_hits), the number of hits allowed in a 60-minute period (hourly_limit), and the time of the reset in seconds since The Epoch (reset_time_in_seconds). ''' url = '%s/account/rate_limit_status.json' % self.base_url json = self._FetchUrl(url, no_cache=True) data = self._ParseAndCheckTwitter(json) return data def MaximumHitFrequency(self): '''Determines the minimum number of seconds that a program must wait before hitting the server again without exceeding the rate_limit imposed for the currently authenticated user. Returns: The minimum second interval that a program must use so as to not exceed the rate_limit imposed for the user. ''' rate_status = self.GetRateLimitStatus() reset_time = rate_status.get('reset_time', None) limit = rate_status.get('remaining_hits', None) if reset_time: # put the reset time into a datetime object reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7]) # find the difference in time between now and the reset time + 1 hour delta = reset + datetime.timedelta(hours=1) - datetime.datetime.utcnow() if not limit: return int(delta.seconds) # determine the minimum number of seconds allowed as a regular interval max_frequency = int(delta.seconds / limit) + 1 # return the number of seconds return max_frequency return 60 def _BuildUrl(self, url, path_elements=None, extra_params=None): # Break url into consituent parts (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) # Add any additional path elements to the path if path_elements: # Filter out the path elements that have a value of None p = [i for i in path_elements if i] if not path.endswith('/'): path += '/' path += '/'.join(p) # Add any additional query parameters to the query string if extra_params and len(extra_params) > 0: extra_query = self._EncodeParameters(extra_params) # Add it to the existing query if query: query += '&' + extra_query else: query = extra_query # Return the rebuilt URL return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) def _InitializeRequestHeaders(self, request_headers): if request_headers: self._request_headers = request_headers else: self._request_headers = {} def _InitializeUserAgent(self): user_agent = 'Python-urllib/%s (python-twitter/%s)' % \ (self._urllib.__version__, __version__) self.SetUserAgent(user_agent) def _InitializeDefaultParameters(self): self._default_params = {} def _DecompressGzippedResponse(self, response): raw_data = response.read() if response.headers.get('content-encoding', None) == 'gzip': url_data = gzip.GzipFile(fileobj=StringIO.StringIO(raw_data)).read() else: url_data = raw_data return url_data def _Encode(self, s): if self._input_encoding: return unicode(s, self._input_encoding).encode('utf-8') else: return unicode(s).encode('utf-8') def _EncodeParameters(self, parameters): '''Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if parameters is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) def _EncodePostData(self, post_data): '''Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if post_data is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) def _ParseAndCheckTwitter(self, json): """Try and parse the JSON returned from Twitter and return an empty dictionary if there is any error. This is a purely defensive check because during some Twitter network outages it will return an HTML failwhale page.""" try: data = simplejson.loads(json) self._CheckForTwitterError(data) except ValueError: if "<title>Twitter / Over capacity</title>" in json: raise TwitterError("Capacity Error") if "<title>Twitter / Error</title>" in json: raise TwitterError("Technical Error") raise TwitterError("json decoding") return data def _CheckForTwitterError(self, data): """Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists. """ # Twitter errors are relatively unlikely, so it is faster # to check first, rather than try and catch the exception if 'error' in data: raise TwitterError(data['error']) if 'errors' in data: raise TwitterError(data['errors']) def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None, use_gzip_compression=None): '''Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [Optional] no_cache: If true, overrides the cache on the current request use_gzip_compression: If True, tells the server to gzip-compress the response. It does not apply to POST requests. Defaults to None, which will get the value to use from the instance variable self._use_gzip [Optional] Returns: A string containing the body of the response. ''' # Build the extra parameters dict extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) if post_data: http_method = "POST" else: http_method = "GET" if self._debugHTTP: _debug = 1 else: _debug = 0 http_handler = self._urllib.HTTPHandler(debuglevel=_debug) https_handler = self._urllib.HTTPSHandler(debuglevel=_debug) opener = self._urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) if use_gzip_compression is None: use_gzip = self._use_gzip else: use_gzip = use_gzip_compression # Set up compression if use_gzip and not post_data: opener.addheaders.append(('Accept-Encoding', 'gzip')) if self._oauth_consumer is not None: if post_data and http_method == "POST": parameters = post_data.copy() req = oauth.Request.from_consumer_and_token(self._oauth_consumer, token=self._oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(self._signature_method_hmac_sha1, self._oauth_consumer, self._oauth_token) headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() else: url = self._BuildUrl(url, extra_params=extra_params) encoded_post_data = self._EncodePostData(post_data) # Open and return the URL immediately if we're not going to cache if encoded_post_data or no_cache or not self._cache or not self._cache_timeout: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) opener.close() else: # Unique keys are a combination of the url and the oAuth Consumer Key if self._consumer_key: key = self._consumer_key + ':' + url else: key = url # See if it has been cached before last_cached = self._cache.GetCachedTime(key) # If the cached version is outdated then fetch another and store it if not last_cached or time.time() >= last_cached + self._cache_timeout: try: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) self._cache.Set(key, url_data) except urllib2.HTTPError, e: print e opener.close() else: url_data = self._cache.Get(key) # Always return the latest version return url_data class _FileCacheError(Exception): '''Base exception class for FileCache related errors''' class _FileCache(object): DEPTH = 3 def __init__(self,root_directory=None): self._InitializeRootDirectory(root_directory) def Get(self,key): path = self._GetPath(key) if os.path.exists(path): return open(path).read() else: return None def Set(self,key,data): path = self._GetPath(key) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise _FileCacheError('%s exists but is not a directory' % directory) temp_fd, temp_path = tempfile.mkstemp() temp_fp = os.fdopen(temp_fd, 'w') temp_fp.write(data) temp_fp.close() if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory)) if os.path.exists(path): os.remove(path) os.rename(temp_path, path) def Remove(self,key): path = self._GetPath(key) if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory )) if os.path.exists(path): os.remove(path) def GetCachedTime(self,key): path = self._GetPath(key) if os.path.exists(path): return os.path.getmtime(path) else: return None def _GetUsername(self): '''Attempt to find the username in a cross-platform fashion.''' try: return os.getenv('USER') or \ os.getenv('LOGNAME') or \ os.getenv('USERNAME') or \ os.getlogin() or \ 'nobody' except (AttributeError, IOError, OSError), e: return 'nobody' def _GetTmpCachePath(self): username = self._GetUsername() cache_directory = 'python.cache_' + username return os.path.join(tempfile.gettempdir(), cache_directory) def _InitializeRootDirectory(self, root_directory): if not root_directory: root_directory = self._GetTmpCachePath() root_directory = os.path.abspath(root_directory) if not os.path.exists(root_directory): os.mkdir(root_directory) if not os.path.isdir(root_directory): raise _FileCacheError('%s exists but is not a directory' % root_directory) self._root_directory = root_directory def _GetPath(self,key): try: hashed_key = md5(key).hexdigest() except TypeError: hashed_key = md5.new(key).hexdigest() return os.path.join(self._root_directory, self._GetPrefix(hashed_key), hashed_key) def _GetPrefix(self,hashed_key): return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
Python
#!/usr/bin/env python """html2text: Turn HTML into equivalent Markdown-structured text.""" __version__ = "2.38" __author__ = "Aaron Swartz (me@aaronsw.com)" __copyright__ = "(C) 2004-2008 Aaron Swartz. GNU GPL 3." __contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes", "Kevin Jay North"] # TODO: # Support decoded entities with unifiable. if not hasattr(__builtins__, 'True'): True, False = 1, 0 import re, sys, urllib, htmlentitydefs, codecs, StringIO, types import sgmllib import urlparse sgmllib.charref = re.compile('&#([xX]?[0-9a-fA-F]+)[^0-9a-fA-F]') try: from textwrap import wrap except: pass # Use Unicode characters instead of their ascii psuedo-replacements UNICODE_SNOB = 0 # Put the links after each paragraph instead of at the end. LINKS_EACH_PARAGRAPH = 0 # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.) BODY_WIDTH = 78 # Don't show internal links (href="#local-anchor") -- corresponding link targets # won't be visible in the plain text file anyway. SKIP_INTERNAL_LINKS = False ### Entity Nonsense ### def name2cp(k): if k == 'apos': return ord("'") if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3 return htmlentitydefs.name2codepoint[k] else: k = htmlentitydefs.entitydefs[k] if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1 return ord(codecs.latin_1_decode(k)[0]) unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"', 'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*', 'ndash':'-', 'oelig':'oe', 'aelig':'ae', 'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a', 'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e', 'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i', 'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o', 'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u'} unifiable_n = {} for k in unifiable.keys(): unifiable_n[name2cp(k)] = unifiable[k] def charref(name): if name[0] in ['x','X']: c = int(name[1:], 16) else: c = int(name) if not UNICODE_SNOB and c in unifiable_n.keys(): return unifiable_n[c] else: return unichr(c) def entityref(c): if not UNICODE_SNOB and c in unifiable.keys(): return unifiable[c] else: try: name2cp(c) except KeyError: return "&" + c else: return unichr(name2cp(c)) def replaceEntities(s): s = s.group(1) if s[0] == "#": return charref(s[1:]) else: return entityref(s) r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));") def unescape(s): return r_unescape.sub(replaceEntities, s) def fixattrs(attrs): # Fix bug in sgmllib.py if not attrs: return attrs newattrs = [] for attr in attrs: newattrs.append((attr[0], unescape(attr[1]))) return newattrs ### End Entity Nonsense ### def onlywhite(line): """Return true if the line does only consist of whitespace characters.""" for c in line: if c is not ' ' and c is not ' ': return c is ' ' return line def optwrap(text): """Wrap all paragraphs in the provided text.""" if not BODY_WIDTH: return text assert wrap, "Requires Python 2.3." result = '' newlines = 0 for para in text.split("\n"): if len(para) > 0: if para[0] is not ' ' and para[0] is not '-' and para[0] is not '*': for line in wrap(para, BODY_WIDTH): result += line + "\n" result += "\n" newlines = 2 else: if not onlywhite(para): result += para + "\n" newlines = 1 else: if newlines < 2: result += "\n" newlines += 1 return result def hn(tag): if tag[0] == 'h' and len(tag) == 2: try: n = int(tag[1]) if n in range(1, 10): return n except ValueError: return 0 class _html2text(sgmllib.SGMLParser): def __init__(self, out=None, baseurl=''): sgmllib.SGMLParser.__init__(self) if out is None: self.out = self.outtextf else: self.out = out self.outtext = u'' self.quiet = 0 self.p_p = 0 self.outcount = 0 self.start = 1 self.space = 0 self.a = [] self.astack = [] self.acount = 0 self.list = [] self.blockquote = 0 self.pre = 0 self.startpre = 0 self.lastWasNL = 0 self.abbr_title = None # current abbreviation definition self.abbr_data = None # last inner HTML (for abbr being defined) self.abbr_list = {} # stack of abbreviations to write later self.baseurl = baseurl def outtextf(self, s): self.outtext += s def close(self): sgmllib.SGMLParser.close(self) self.pbr() self.o('', 0, 'end') return self.outtext def handle_charref(self, c): self.o(charref(c)) def handle_entityref(self, c): self.o(entityref(c)) def unknown_starttag(self, tag, attrs): self.handle_tag(tag, attrs, 1) def unknown_endtag(self, tag): self.handle_tag(tag, None, 0) def previousIndex(self, attrs): """ returns the index of certain set of attributes (of a link) in the self.a list If the set of attributes is not found, returns None """ if not attrs.has_key('href'): return None i = -1 for a in self.a: i += 1 match = 0 if a.has_key('href') and a['href'] == attrs['href']: if a.has_key('title') or attrs.has_key('title'): if (a.has_key('title') and attrs.has_key('title') and a['title'] == attrs['title']): match = True else: match = True if match: return i def handle_tag(self, tag, attrs, start): attrs = fixattrs(attrs) if hn(tag): self.p() if start: self.o(hn(tag)*"#" + ' ') if tag in ['p', 'div']: self.p() if tag == "br" and start: self.o(" \n") if tag == "hr" and start: self.p() self.o("* * *") self.p() if tag in ["head", "style", 'script']: if start: self.quiet += 1 else: self.quiet -= 1 if tag in ["body"]: self.quiet = 0 # sites like 9rules.com never close <head> if tag == "blockquote": if start: self.p(); self.o('> ', 0, 1); self.start = 1 self.blockquote += 1 else: self.blockquote -= 1 self.p() if tag in ['em', 'i', 'u']: self.o("_") if tag in ['strong', 'b']: self.o("**") if tag == "code" and not self.pre: self.o('`') #TODO: `` `this` `` if tag == "abbr": if start: attrsD = {} for (x, y) in attrs: attrsD[x] = y attrs = attrsD self.abbr_title = None self.abbr_data = '' if attrs.has_key('title'): self.abbr_title = attrs['title'] else: if self.abbr_title != None: self.abbr_list[self.abbr_data] = self.abbr_title self.abbr_title = None self.abbr_data = '' if tag == "a": if start: attrsD = {} for (x, y) in attrs: attrsD[x] = y attrs = attrsD if attrs.has_key('href') and not (SKIP_INTERNAL_LINKS and attrs['href'].startswith('#')): self.astack.append(attrs) self.o("[") else: self.astack.append(None) else: if self.astack: a = self.astack.pop() if a: i = self.previousIndex(a) if i is not None: a = self.a[i] else: self.acount += 1 a['count'] = self.acount a['outcount'] = self.outcount self.a.append(a) self.o("][" + `a['count']` + "]") if tag == "img" and start: attrsD = {} for (x, y) in attrs: attrsD[x] = y attrs = attrsD if attrs.has_key('src'): attrs['href'] = attrs['src'] alt = attrs.get('alt', '') i = self.previousIndex(attrs) if i is not None: attrs = self.a[i] else: self.acount += 1 attrs['count'] = self.acount attrs['outcount'] = self.outcount self.a.append(attrs) self.o("![") self.o(alt) self.o("]["+`attrs['count']`+"]") if tag == 'dl' and start: self.p() if tag == 'dt' and not start: self.pbr() if tag == 'dd' and start: self.o(' ') if tag == 'dd' and not start: self.pbr() if tag in ["ol", "ul"]: if start: self.list.append({'name':tag, 'num':0}) else: if self.list: self.list.pop() self.p() if tag == 'li': if start: self.pbr() if self.list: li = self.list[-1] else: li = {'name':'ul', 'num':0} self.o(" "*len(self.list)) #TODO: line up <ol><li>s > 9 correctly. if li['name'] == "ul": self.o("* ") elif li['name'] == "ol": li['num'] += 1 self.o(`li['num']`+". ") self.start = 1 else: self.pbr() if tag in ["table", "tr"] and start: self.p() if tag == 'td': self.pbr() if tag == "pre": if start: self.startpre = 1 self.pre = 1 else: self.pre = 0 self.p() def pbr(self): if self.p_p == 0: self.p_p = 1 def p(self): self.p_p = 2 def o(self, data, puredata=0, force=0): if self.abbr_data is not None: self.abbr_data += data if not self.quiet: if puredata and not self.pre: data = re.sub('\s+', ' ', data) if data and data[0] == ' ': self.space = 1 data = data[1:] if not data and not force: return if self.startpre: #self.out(" :") #TODO: not output when already one there self.startpre = 0 bq = (">" * self.blockquote) if not (force and data and data[0] == ">") and self.blockquote: bq += " " if self.pre: bq += " " data = data.replace("\n", "\n"+bq) if self.start: self.space = 0 self.p_p = 0 self.start = 0 if force == 'end': # It's the end. self.p_p = 0 self.out("\n") self.space = 0 if self.p_p: self.out(('\n'+bq)*self.p_p) self.space = 0 if self.space: if not self.lastWasNL: self.out(' ') self.space = 0 if self.a and ((self.p_p == 2 and LINKS_EACH_PARAGRAPH) or force == "end"): if force == "end": self.out("\n") newa = [] for link in self.a: if self.outcount > link['outcount']: self.out(" ["+`link['count']`+"]: " + urlparse.urljoin(self.baseurl, link['href'])) if link.has_key('title'): self.out(" ("+link['title']+")") self.out("\n") else: newa.append(link) if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done. self.a = newa if self.abbr_list and force == "end": for abbr, definition in self.abbr_list.items(): self.out(" *[" + abbr + "]: " + definition + "\n") self.p_p = 0 self.out(data) self.lastWasNL = data and data[-1] == '\n' self.outcount += 1 def handle_data(self, data): if r'\/script>' in data: self.quiet -= 1 self.o(data, 1) def unknown_decl(self, data): pass def wrapwrite(text): sys.stdout.write(text.encode('utf8')) def html2text_file(html, out=wrapwrite, baseurl=''): h = _html2text(out, baseurl) h.feed(html) h.feed("") return h.close() def html2text(html, baseurl=''): return optwrap(html2text_file(html, None, baseurl)) if __name__ == "__main__": baseurl = '' if sys.argv[1:]: arg = sys.argv[1] if arg.startswith('http://'): baseurl = arg j = urllib.urlopen(baseurl) try: from feedparser import _getCharacterEncoding as enc except ImportError: enc = lambda x, y: ('utf-8', 1) text = j.read() encoding = enc(j.headers, text)[0] if encoding == 'us-ascii': encoding = 'utf-8' data = text.decode(encoding) else: encoding = 'utf8' if len(sys.argv) > 2: encoding = sys.argv[2] data = open(arg, 'r').read().decode(encoding) else: data = sys.stdin.read().decode('utf8') wrapwrite(html2text(data, baseurl))
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s पंक्तियाँ मिटाएँ', '%s rows updated': '%s पंक्तियाँ अद्यतन', 'About': 'About', 'About Us': 'About Us', 'Access Control': 'Access Control', 'Administrative interface': 'प्रशासनिक इंटरफेस के लिए यहाँ क्लिक करें', 'Ajax Recipes': 'Ajax Recipes', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available databases and tables': 'उपलब्ध डेटाबेस और तालिका', 'Body': 'Body', 'Buy this book': 'Buy this book', 'Cancel': 'Cancel', 'Cannot be empty': 'खाली नहीं हो सकता', 'Change Password': 'पासवर्ड बदलें', 'Change the sites displayed language': 'Change the sites displayed language', 'Check to delete': 'हटाने के लिए चुनें', 'Community': 'Community', 'Contact Us': 'Contact Us', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'वर्तमान अनुरोध', 'Current response': 'वर्तमान प्रतिक्रिया', 'Current session': 'वर्तमान सेशन', 'DB Model': 'DB Model', 'Database': 'Database', 'Date': 'Date', 'Delete:': 'मिटाना:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Developer': 'Developer', 'Documentation': 'Documentation', 'Download': 'Download', 'Edit': 'Edit', 'Edit Page': 'Edit Page', 'Edit Profile': 'प्रोफ़ाइल संपादित करें', 'Edit This App': 'Edit This App', 'Edit current record': 'वर्तमान रेकॉर्ड संपादित करें ', 'Errors': 'Errors', 'Errors!': 'Errors!', 'FAQ': 'FAQ', 'Format': 'Format', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Gallery': 'Gallery', 'Groups': 'Groups', 'Hello World': 'Hello World', 'Hello from MyApp': 'Hello from MyApp', 'History': 'History', 'Home': 'Home', 'Id': 'Id', 'Import/Export': 'आयात / निर्यात', 'Index': 'Index', 'Internal State': 'आंतरिक स्थिति', 'Introduction': 'Introduction', 'Invalid Query': 'अमान्य प्रश्न', 'Language Menu': 'Language Menu', 'Layout': 'Layout', 'Layouts': 'Layouts', 'Live chat': 'Live chat', 'Login': 'लॉग इन', 'Logout': 'लॉग आउट', 'Lost Password': 'पासवर्ड खो गया', 'Main Menu': 'Main Menu', 'Menu Model': 'Menu Model', 'New Record': 'नया रेकॉर्ड', 'No databases in this application': 'इस अनुप्रयोग में कोई डेटाबेस नहीं हैं', 'Online examples': 'ऑनलाइन उदाहरण के लिए यहाँ क्लिक करें', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Page History': 'Page History', 'Page Not Found!': 'Page Not Found!', 'Page Preview': 'Page Preview', 'Page format converted!': 'Page format converted!', 'Page saved': 'Page saved', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'Preview': 'Preview', 'Products': 'Products', 'Python': 'Python', 'Query:': 'प्रश्न:', 'Quick Examples': 'Quick Examples', 'Readme': 'Readme', 'Recipes': 'Recipes', 'Register': 'पंजीकृत (रजिस्टर) करना ', 'Resources': 'Resources', 'Rows in table': 'तालिका में पंक्तियाँ ', 'Rows selected': 'चयनित (चुने गये) पंक्तियाँ ', 'Save': 'Save', 'Semantic': 'Semantic', 'Services': 'Services', 'Stylesheet': 'Stylesheet', 'Subtitle': 'Subtitle', 'Support': 'Support', 'Sure you want to delete this object?': 'सुनिश्चित हैं कि आप इस वस्तु को हटाना चाहते हैं?', 'Testimonials': 'Testimonials', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'The Core': 'The Core', 'The Views': 'The Views', 'The output of the file is a dictionary that was rendered by the view': 'The output of the file is a dictionary that was rendered by the view', 'This App': 'This App', 'This is a copy of the scaffolding application': 'This is a copy of the scaffolding application', 'Title': 'Title', 'Twitter': 'Twitter', 'Update:': 'अद्यतन करना:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'User': 'User', 'User Voice': 'User Voice', 'Videos': 'Videos', 'View': 'View', 'Viewing page version: %s': 'Viewing page version: %s', 'Web2py': 'Web2py', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'वेब२पाइ (web2py) में आपका स्वागत है', 'Which called the function': 'Which called the function', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url': 'You visited the url', 'about': 'about', 'admin': 'admin', 'appadmin is disabled because insecure channel': 'अप आडमिन (appadmin) अक्षम है क्योंकि असुरक्षित चैनल', 'cache': 'cache', 'change password': 'change password', 'customize me!': 'मुझे अनुकूलित (कस्टमाइज़) करें!', 'data uploaded': 'डाटा अपलोड सम्पन्न ', 'database': 'डेटाबेस', 'database %s select': 'डेटाबेस %s चुनी हुई', 'db': 'db', 'demo': 'demo', 'design': 'रचना करें', 'done!': 'हो गया!', 'edit profile': 'edit profile', 'export as csv file': 'csv फ़ाइल के रूप में निर्यात', 'flatpages': 'flatpages', 'insert new': 'नया डालें', 'insert new %s': 'नया %s डालें', 'invalid request': 'अवैध अनुरोध', 'license': 'license', 'located in the file': 'located in the file', 'login': 'login', 'logout': 'logout', 'new record inserted': 'नया रेकॉर्ड डाला', 'next 100 rows': 'अगले 100 पंक्तियाँ', 'not authorized': 'not authorized', 'or import from csv file': 'या csv फ़ाइल से आयात', 'plugin_flatpages': 'plugin_flatpages', 'previous 100 rows': 'पिछले 100 पंक्तियाँ', 'readme': 'readme', 'record': 'record', 'record does not exist': 'रिकॉर्ड मौजूद नहीं है', 'record id': 'रिकॉर्ड पहचानकर्ता (आईडी)', 'register': 'register', 'roadmap': 'roadmap', 'selected': 'चुना हुआ', 'state': 'स्थिति', 'table': 'तालिका', 'unable to parse csv file': 'csv फ़ाइल पार्स करने में असमर्थ', 'universal cake': 'universal cake', 'voice of access': 'voice of access', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': 'Wierszy usuniętych: %s', '%s rows updated': 'Wierszy uaktualnionych: %s', 'About': 'About', 'About Us': 'About Us', 'Access Control': 'Access Control', 'Administrative interface': 'Kliknij aby przejść do panelu administracyjnego', 'Ajax Recipes': 'Ajax Recipes', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available databases and tables': 'Dostępne bazy danych i tabele', 'Body': 'Body', 'Buy this book': 'Buy this book', 'Cancel': 'Cancel', 'Cannot be empty': 'Nie może być puste', 'Change Password': 'Change Password', 'Change the sites displayed language': 'Change the sites displayed language', 'Check to delete': 'Zaznacz aby usunąć', 'Community': 'Community', 'Contact Us': 'Contact Us', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Aktualne żądanie', 'Current response': 'Aktualna odpowiedź', 'Current session': 'Aktualna sesja', 'DB Model': 'DB Model', 'Database': 'Database', 'Date': 'Date', 'Delete:': 'Usuń:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Developer': 'Developer', 'Documentation': 'Documentation', 'Download': 'Download', 'Edit': 'Edit', 'Edit Page': 'Edit Page', 'Edit Profile': 'Edit Profile', 'Edit This App': 'Edit This App', 'Edit current record': 'Edytuj aktualny rekord', 'Errors': 'Errors', 'Errors!': 'Errors!', 'FAQ': 'FAQ', 'Format': 'Format', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Gallery': 'Gallery', 'Groups': 'Groups', 'Hello World': 'Witaj Świecie', 'History': 'History', 'Home': 'Home', 'Id': 'Id', 'Import/Export': 'Importuj/eksportuj', 'Index': 'Index', 'Internal State': 'Stan wewnętrzny', 'Introduction': 'Introduction', 'Invalid Query': 'Błędne zapytanie', 'Language Menu': 'Language Menu', 'Layout': 'Layout', 'Layouts': 'Layouts', 'Live chat': 'Live chat', 'Login': 'Zaloguj', 'Logout': 'Logout', 'Lost Password': 'Przypomnij hasło', 'Main Menu': 'Main Menu', 'Menu Model': 'Menu Model', 'New Record': 'Nowy rekord', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Online examples': 'Kliknij aby przejść do interaktywnych przykładów', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Page History': 'Page History', 'Page Not Found!': 'Page Not Found!', 'Page Preview': 'Page Preview', 'Page format converted!': 'Page format converted!', 'Page saved': 'Page saved', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'Preview': 'Preview', 'Products': 'Products', 'Python': 'Python', 'Query:': 'Zapytanie:', 'Quick Examples': 'Quick Examples', 'Readme': 'Readme', 'Recipes': 'Recipes', 'Register': 'Zarejestruj', 'Resources': 'Resources', 'Rows in table': 'Wiersze w tabeli', 'Rows selected': 'Wybrane wiersze', 'Save': 'Save', 'Semantic': 'Semantic', 'Services': 'Services', 'Stylesheet': 'Stylesheet', 'Subtitle': 'Subtitle', 'Support': 'Support', 'Sure you want to delete this object?': 'Czy na pewno chcesz usunąć ten obiekt?', 'Testimonials': 'Testimonials', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'wartość\'". Takie coś jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', 'The Core': 'The Core', 'The Views': 'The Views', 'The output of the file is a dictionary that was rendered by the view': 'The output of the file is a dictionary that was rendered by the view', 'This App': 'This App', 'This is a copy of the scaffolding application': 'This is a copy of the scaffolding application', 'Title': 'Title', 'Twitter': 'Twitter', 'Update:': 'Uaktualnij:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Użyj (...)&(...) jako AND, (...)|(...) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapytań.', 'User': 'User', 'User Voice': 'User Voice', 'Videos': 'Videos', 'View': 'View', 'Viewing page version: %s': 'Viewing page version: %s', 'Web2py': 'Web2py', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Witaj w web2py', 'Which called the function': 'Which called the function', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url': 'You visited the url', 'about': 'about', 'admin': 'admin', 'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel', 'cache': 'cache', 'change password': 'change password', 'customize me!': 'dostosuj mnie!', 'data uploaded': 'dane wysłane', 'database': 'baza danych', 'database %s select': 'wybór z bazy danych %s', 'db': 'baza danych', 'demo': 'demo', 'design': 'projektuj', 'done!': 'zrobione!', 'edit profile': 'edit profile', 'export as csv file': 'eksportuj jako plik csv', 'flatpages': 'flatpages', 'insert new': 'wstaw nowy rekord tabeli', 'insert new %s': 'wstaw nowy rekord do tabeli %s', 'invalid request': 'Błędne żądanie', 'license': 'license', 'located in the file': 'located in the file', 'login': 'login', 'logout': 'logout', 'new record inserted': 'nowy rekord został wstawiony', 'next 100 rows': 'następne 100 wierszy', 'not authorized': 'not authorized', 'or import from csv file': 'lub zaimportuj z pliku csv', 'plugin_flatpages': 'plugin_flatpages', 'previous 100 rows': 'poprzednie 100 wierszy', 'readme': 'readme', 'record': 'record', 'record does not exist': 'rekord nie istnieje', 'record id': 'id rekordu', 'register': 'register', 'roadmap': 'roadmap', 'selected': 'wybranych', 'state': 'stan', 'table': 'tabela', 'unable to parse csv file': 'nie można sparsować pliku csv', 'universal cake': 'universal cake', 'voice of access': 'voice of access', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s filas eliminadas', '%s rows updated': '%s filas actualizadas', '(something like "it-it")': '(algo como "it-it")', 'A new version of web2py is available': 'Hay una nueva versión de web2py disponible', 'A new version of web2py is available: %s': 'Hay una nueva versión de web2py disponible: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENCION: Inicio de sesión requiere una conexión segura (HTTPS) o localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATENCION: NO EJECUTE VARIAS PRUEBAS SIMULTANEAMENTE, NO SON THREAD SAFE.', 'ATTENTION: you cannot edit the running application!': 'ATENCION: no puede modificar la aplicación que se ejecuta!', 'About': 'Acerca de', 'About Us': 'About Us', 'About application': 'Acerca de la aplicación', 'Access Control': 'Access Control', 'Admin is disabled because insecure channel': 'Admin deshabilitado, el canal no es seguro', 'Admin is disabled because unsecure channel': 'Admin deshabilitado, el canal no es seguro', 'Administrative interface': 'Interfaz administrativa', 'Administrator Password:': 'Contraseña del Administrador:', 'Ajax Recipes': 'Ajax Recipes', 'Are you sure you want to delete file "%s"?': '¿Está seguro que desea eliminar el archivo "%s"?', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Are you sure you want to uninstall application "%s"': '¿Está seguro que desea desinstalar la aplicación "%s"', 'Are you sure you want to uninstall application "%s"?': '¿Está seguro que desea desinstalar la aplicación "%s"?', 'Authentication': 'Autenticación', 'Available databases and tables': 'Bases de datos y tablas disponibles', 'Body': 'Body', 'Buy this book': 'Buy this book', 'Cancel': 'Cancel', 'Cannot be empty': 'No puede estar vacío', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'No se puede compilar: hay errores en su aplicación. Depure, corrija errores y vuelva a intentarlo.', 'Change Password': 'Cambie Contraseña', 'Change the sites displayed language': 'Change the sites displayed language', 'Check to delete': 'Marque para eliminar', 'Client IP': 'IP del Cliente', 'Community': 'Community', 'Contact Us': 'Contact Us', 'Controller': 'Controlador', 'Controllers': 'Controladores', 'Copyright': 'Derechos de autor', 'Create new application': 'Cree una nueva aplicación', 'Current request': 'Solicitud en curso', 'Current response': 'Respuesta en curso', 'Current session': 'Sesión en curso', 'DB Model': 'Modelo "db"', 'DESIGN': 'DISEÑO', 'Database': 'Base de datos', 'Date': 'Date', 'Date and Time': 'Fecha y Hora', 'Delete': 'Elimine', 'Delete:': 'Elimine:', 'Demo': 'Demo', 'Deploy on Google App Engine': 'Instale en Google App Engine', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Descripción', 'Design for': 'Diseño para', 'Developer': 'Developer', 'Documentation': 'Documentación', 'Download': 'Download', 'E-mail': 'Correo electrónico', 'EDIT': 'EDITAR', 'Edit': 'Editar', 'Edit Page': 'Edit Page', 'Edit Profile': 'Editar Perfil', 'Edit This App': 'Edite esta App', 'Edit application': 'Editar aplicación', 'Edit current record': 'Edite el registro actual', 'Editing file': 'Editando archivo', 'Editing file "%s"': 'Editando archivo "%s"', 'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"', 'Errors': 'Errors', 'Errors!': 'Errors!', 'FAQ': 'FAQ', 'First name': 'Nombre', 'Format': 'Format', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].', 'Gallery': 'Gallery', 'Group ID': 'ID de Grupo', 'Groups': 'Groups', 'Hello World': 'Hola Mundo', 'History': 'History', 'Home': 'Home', 'Id': 'Id', 'Import/Export': 'Importar/Exportar', 'Index': 'Indice', 'Installed applications': 'Aplicaciones instaladas', 'Internal State': 'Estado Interno', 'Introduction': 'Introduction', 'Invalid Query': 'Consulta inválida', 'Invalid action': 'Acción inválida', 'Invalid email': 'Correo inválido', 'Language Menu': 'Language Menu', 'Language files (static strings) updated': 'Archivos de lenguaje (cadenas estáticas) actualizados', 'Languages': 'Lenguajes', 'Last name': 'Apellido', 'Last saved on:': 'Guardado en:', 'Layout': 'Diseño de página', 'Layouts': 'Layouts', 'License for': 'Licencia para', 'Live chat': 'Live chat', 'Login': 'Inicio de sesión', 'Login to the Administrative Interface': 'Inicio de sesión para la Interfaz Administrativa', 'Logout': 'Fin de sesión', 'Lost Password': 'Contraseña perdida', 'Main Menu': 'Menú principal', 'Menu Model': 'Modelo "menu"', 'Models': 'Modelos', 'Modules': 'Módulos', 'NO': 'NO', 'Name': 'Nombre', 'New Record': 'Registro nuevo', 'No databases in this application': 'No hay bases de datos en esta aplicación', 'Online examples': 'Ejemplos en línea', 'Origin': 'Origen', 'Original/Translation': 'Original/Traducción', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Page History': 'Page History', 'Page Not Found!': 'Page Not Found!', 'Page Preview': 'Page Preview', 'Page format converted!': 'Page format converted!', 'Page saved': 'Page saved', 'Password': 'Contraseña', 'Peeking at file': 'Visualizando archivo', 'Plugins': 'Plugins', 'Powered by': 'Este sitio usa', 'Preface': 'Preface', 'Preview': 'Preview', 'Products': 'Products', 'Python': 'Python', 'Query:': 'Consulta:', 'Quick Examples': 'Quick Examples', 'Readme': 'Readme', 'Recipes': 'Recipes', 'Record ID': 'ID de Registro', 'Register': 'Registrese', 'Registration key': 'Contraseña de Registro', 'Reset Password key': 'Reset Password key', 'Resolve Conflict file': 'archivo Resolución de Conflicto', 'Resources': 'Resources', 'Role': 'Rol', 'Rows in table': 'Filas en la tabla', 'Rows selected': 'Filas seleccionadas', 'Save': 'Save', 'Saved file hash:': 'Hash del archivo guardado:', 'Semantic': 'Semantic', 'Services': 'Services', 'Static files': 'Archivos estáticos', 'Stylesheet': 'Hoja de estilo', 'Subtitle': 'Subtitle', 'Support': 'Support', 'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?', 'Table name': 'Nombre de la tabla', 'Testimonials': 'Testimonials', 'Testing application': 'Probando aplicación', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "consulta" es una condición como "db.tabla1.campo1==\'valor\'". Algo como "db.tabla1.campo1==db.tabla2.campo2" resulta en un JOIN SQL.', 'The Core': 'The Core', 'The Views': 'The Views', 'The output of the file is a dictionary that was rendered by the view': 'La salida del archivo es un diccionario escenificado por la vista', 'There are no controllers': 'No hay controladores', 'There are no models': 'No hay modelos', 'There are no modules': 'No hay módulos', 'There are no static files': 'No hay archivos estáticos', 'There are no translators, only default language is supported': 'No hay traductores, sólo el lenguaje por defecto es soportado', 'There are no views': 'No hay vistas', 'This App': 'This App', 'This is a copy of the scaffolding application': 'Esta es una copia de la aplicación de andamiaje', 'This is the %(filename)s template': 'Esta es la plantilla %(filename)s', 'Ticket': 'Tiquete', 'Timestamp': 'Timestamp', 'Title': 'Title', 'Twitter': 'Twitter', 'Unable to check for upgrades': 'No es posible verificar la existencia de actualizaciones', 'Unable to download': 'No es posible la descarga', 'Unable to download app': 'No es posible descarga la aplicación', 'Update:': 'Actualice:', 'Upload existing application': 'Suba esta aplicación', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, y ~(...) para NOT, para crear consultas más complejas.', 'User': 'User', 'User ID': 'ID de Usuario', 'User Voice': 'User Voice', 'Videos': 'Videos', 'View': 'Vista', 'Viewing page version: %s': 'Viewing page version: %s', 'Views': 'Vistas', 'Web2py': 'Web2py', 'Welcome': 'Welcome', 'Welcome %s': 'Bienvenido %s', 'Welcome to web2py': 'Bienvenido a web2py', 'Which called the function': 'La cual llamó la función', 'YES': 'SI', 'You are successfully running web2py': 'Usted está ejecutando web2py exitosamente', 'You can modify this application and adapt it to your needs': 'Usted puede modificar esta aplicación y adaptarla a sus necesidades', 'You visited the url': 'Usted visitó la url', 'about': 'acerca de', 'additional code for your application': 'código adicional para su aplicación', 'admin': 'admin', 'admin disabled because no admin password': ' por falta de contraseña', 'admin disabled because not supported on google app engine': 'admin deshabilitado, no es soportado en GAE', 'admin disabled because unable to access password file': 'admin deshabilitado, imposible acceder al archivo con la contraseña', 'and rename it (required):': 'y renombrela (requerido):', 'and rename it:': ' y renombrelo:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'admin deshabilitado, el canal no es seguro', 'application "%s" uninstalled': 'aplicación "%s" desinstalada', 'application compiled': 'aplicación compilada', 'application is compiled and cannot be designed': 'la aplicación está compilada y no puede ser modificada', 'cache': 'cache', 'cache, errors and sessions cleaned': 'cache, errores y sesiones eliminados', 'cannot create file': 'no es posible crear archivo', 'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"', 'change password': 'cambie contraseña', 'check all': 'marcar todos', 'clean': 'limpiar', 'click to check for upgrades': 'haga clic para buscar actualizaciones', 'compile': 'compilar', 'compiled application removed': 'aplicación compilada removida', 'controllers': 'controladores', 'create file with filename:': 'cree archivo con nombre:', 'create new application:': 'nombre de la nueva aplicación:', 'crontab': 'crontab', 'currently saved or': 'actualmente guardado o', 'customize me!': 'Adaptame!', 'data uploaded': 'datos subidos', 'database': 'base de datos', 'database %s select': 'selección en base de datos %s', 'database administration': 'administración base de datos', 'db': 'db', 'defines tables': 'define tablas', 'delete': 'eliminar', 'delete all checked': 'eliminar marcados', 'demo': 'demo', 'design': 'modificar', 'done!': 'listo!', 'edit': 'editar', 'edit controller': 'editar controlador', 'edit profile': 'editar perfil', 'errors': 'errores', 'export as csv file': 'exportar como archivo CSV', 'exposes': 'expone', 'extends': 'extiende', 'failed to reload module': 'recarga del módulo ha fallado', 'file "%(filename)s" created': 'archivo "%(filename)s" creado', 'file "%(filename)s" deleted': 'archivo "%(filename)s" eliminado', 'file "%(filename)s" uploaded': 'archivo "%(filename)s" subido', 'file "%(filename)s" was not deleted': 'archivo "%(filename)s" no fué eliminado', 'file "%s" of %s restored': 'archivo "%s" de %s restaurado', 'file changed on disk': 'archivo modificado en el disco', 'file does not exist': 'archivo no existe', 'file saved on %(time)s': 'archivo guardado %(time)s', 'file saved on %s': 'archivo guardado %s', 'flatpages': 'flatpages', 'help': 'ayuda', 'htmledit': 'htmledit', 'includes': 'incluye', 'insert new': 'inserte nuevo', 'insert new %s': 'inserte nuevo %s', 'internal error': 'error interno', 'invalid password': 'contraseña inválida', 'invalid request': 'solicitud inválida', 'invalid ticket': 'tiquete inválido', 'language file "%(filename)s" created/updated': 'archivo de lenguaje "%(filename)s" creado/actualizado', 'languages': 'lenguajes', 'languages updated': 'lenguajes actualizados', 'license': 'license', 'loading...': 'cargando...', 'located in the file': 'localizada en el archivo', 'login': 'inicio de sesión', 'logout': 'fin de sesión', 'lost password?': '¿olvido la contraseña?', 'merge': 'combinar', 'models': 'modelos', 'modules': 'módulos', 'new application "%s" created': 'nueva aplicación "%s" creada', 'new record inserted': 'nuevo registro insertado', 'next 100 rows': '100 filas siguientes', 'not authorized': 'not authorized', 'or import from csv file': 'o importar desde archivo CSV', 'or provide application url:': 'o provea URL de la aplicación:', 'pack all': 'empaquetar todo', 'pack compiled': 'empaquete compiladas', 'plugin_flatpages': 'plugin_flatpages', 'previous 100 rows': '100 filas anteriores', 'readme': 'readme', 'record': 'registro', 'record does not exist': 'el registro no existe', 'record id': 'id de registro', 'register': 'registrese', 'remove compiled': 'eliminar compiladas', 'restore': 'restaurar', 'revert': 'revertir', 'roadmap': 'roadmap', 'save': 'guardar', 'selected': 'seleccionado(s)', 'session expired': 'sesión expirada', 'shell': 'shell', 'site': 'sitio', 'some files could not be removed': 'algunos archivos no pudieron ser removidos', 'state': 'estado', 'static': 'estáticos', 'table': 'tabla', 'test': 'probar', 'the application logic, each URL path is mapped in one exposed function in the controller': 'la lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador', 'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos', 'the presentations layer, views are also known as templates': 'la capa de presentación, las vistas también son llamadas plantillas', 'these files are served without processing, your images go here': 'estos archivos son servidos sin procesar, sus imágenes van aquí', 'to previous version.': 'a la versión previa.', 'translation strings for the application': 'cadenas de caracteres de traducción para la aplicación', 'try': 'intente', 'try something like': 'intente algo como', 'unable to create application "%s"': 'no es posible crear la aplicación "%s"', 'unable to delete file "%(filename)s"': 'no es posible eliminar el archivo "%(filename)s"', 'unable to parse csv file': 'no es posible analizar el archivo CSV', 'unable to uninstall "%s"': 'no es posible instalar "%s"', 'uncheck all': 'desmarcar todos', 'uninstall': 'desinstalar', 'universal cake': 'universal cake', 'update': 'actualizar', 'update all languages': 'actualizar todos los lenguajes', 'upload application:': 'subir aplicación:', 'upload file:': 'suba archivo:', 'versioning': 'versiones', 'view': 'vista', 'views': 'vistas', 'voice of access': 'voice of access', 'web2py Recent Tweets': 'Tweets Recientes de web2py', 'web2py is up to date': 'web2py está actualizado', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '%s rows deleted': '%s righe ("record") cancellate', '%s rows updated': '%s righe ("record") modificate', 'About': 'About', 'About Us': 'About Us', 'Access Control': 'Access Control', 'Administrative interface': 'Interfaccia amministrativa', 'Ajax Recipes': 'Ajax Recipes', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available databases and tables': 'Database e tabelle disponibili', 'Body': 'Body', 'Buy this book': 'Buy this book', 'Cancel': 'Cancel', 'Cannot be empty': 'Non può essere vuoto', 'Change the sites displayed language': 'Change the sites displayed language', 'Check to delete': 'Seleziona per cancellare', 'Client IP': 'Client IP', 'Community': 'Community', 'Contact Us': 'Contact Us', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Richiesta (request) corrente', 'Current response': 'Risposta (response) corrente', 'Current session': 'Sessione (session) corrente', 'DB Model': 'Modello di DB', 'Database': 'Database', 'Date': 'Date', 'Delete:': 'Cancella:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Descrizione', 'Developer': 'Developer', 'Documentation': 'Documentazione', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit': 'Modifica', 'Edit Page': 'Edit Page', 'Edit This App': 'Modifica questa applicazione', 'Edit current record': 'Modifica record corrente', 'Errors': 'Errors', 'Errors!': 'Errors!', 'FAQ': 'FAQ', 'First name': 'Nome', 'Format': 'Format', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Gallery': 'Gallery', 'Group ID': 'ID Gruppo', 'Groups': 'Groups', 'Hello World': 'Salve Mondo', 'Hello World in a flash!': 'Salve Mondo in un flash!', 'History': 'History', 'Home': 'Home', 'Id': 'Id', 'Import/Export': 'Importa/Esporta', 'Index': 'Indice', 'Internal State': 'Stato interno', 'Introduction': 'Introduction', 'Invalid Query': 'Richiesta (query) non valida', 'Invalid email': 'Email non valida', 'Language Menu': 'Language Menu', 'Last name': 'Cognome', 'Layout': 'Layout', 'Layouts': 'Layouts', 'Live chat': 'Live chat', 'Main Menu': 'Menu principale', 'Menu Model': 'Menu Modelli', 'Name': 'Nome', 'New Record': 'Nuovo elemento (record)', 'No databases in this application': 'Nessun database presente in questa applicazione', 'Online examples': 'Vedere gli esempi', 'Origin': 'Origine', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Page History': 'Page History', 'Page Not Found!': 'Page Not Found!', 'Page Preview': 'Page Preview', 'Page format converted!': 'Page format converted!', 'Page saved': 'Page saved', 'Password': 'Password', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'Preview': 'Preview', 'Products': 'Products', 'Python': 'Python', 'Query:': 'Richiesta (query):', 'Quick Examples': 'Quick Examples', 'Readme': 'Readme', 'Recipes': 'Recipes', 'Record ID': 'Record ID', 'Registration key': 'Chiave di Registazione', 'Reset Password key': 'Resetta chiave Password ', 'Resources': 'Resources', 'Role': 'Ruolo', 'Rows in table': 'Righe nella tabella', 'Rows selected': 'Righe selezionate', 'Save': 'Save', 'Semantic': 'Semantic', 'Services': 'Services', 'Stylesheet': 'Foglio di stile (stylesheet)', 'Subtitle': 'Subtitle', 'Support': 'Support', 'Sure you want to delete this object?': 'Vuoi veramente cancellare questo oggetto?', 'Table name': 'Nome tabella', 'Testimonials': 'Testimonials', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La richiesta (query) è una condizione come ad esempio "db.tabella1.campo1==\'valore\'". Una condizione come "db.tabella1.campo1==db.tabella2.campo2" produce un "JOIN" SQL.', 'The Core': 'The Core', 'The Views': 'The Views', 'The output of the file is a dictionary that was rendered by the view': 'L\'output del file è un "dictionary" che è stato visualizzato dalla vista', 'This App': 'This App', 'This is a copy of the scaffolding application': "Questa è una copia dell'applicazione di base (scaffold)", 'Timestamp': 'Ora (timestamp)', 'Title': 'Title', 'Twitter': 'Twitter', 'Update:': 'Aggiorna:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Per costruire richieste (query) più complesse si usano (...)&(...) come "e" (AND), (...)|(...) come "o" (OR), e ~(...) come negazione (NOT).', 'User': 'User', 'User ID': 'ID Utente', 'User Voice': 'User Voice', 'Videos': 'Videos', 'View': 'Vista', 'Viewing page version: %s': 'Viewing page version: %s', 'Web2py': 'Web2py', 'Welcome %s': 'Benvenuto %s', 'Welcome to web2py': 'Benvenuto su web2py', 'Which called the function': 'che ha chiamato la funzione', 'You are successfully running web2py': 'Stai eseguendo web2py con successo', 'You can modify this application and adapt it to your needs': 'Puoi modificare questa applicazione adattandola alle tue necessità', 'You visited the url': "Hai visitato l'URL", 'about': 'about', 'admin': 'admin', 'appadmin is disabled because insecure channel': 'Amministrazione (appadmin) disabilitata: comunicazione non sicura', 'cache': 'cache', 'change password': 'Cambia password', 'customize me!': 'Personalizzami!', 'data uploaded': 'dati caricati', 'database': 'database', 'database %s select': 'database %s select', 'db': 'db', 'demo': 'demo', 'design': 'progetta', 'done!': 'fatto!', 'edit profile': 'modifica profilo', 'export as csv file': 'esporta come file CSV', 'flatpages': 'flatpages', 'hello world': 'salve mondo', 'insert new': 'inserisci nuovo', 'insert new %s': 'inserisci nuovo %s', 'invalid request': 'richiesta non valida', 'license': 'license', 'located in the file': 'presente nel file', 'login': 'accesso', 'logout': 'uscita', 'lost password?': 'dimenticato la password?', 'new record inserted': 'nuovo record inserito', 'next 100 rows': 'prossime 100 righe', 'not authorized': 'non autorizzato', 'or import from csv file': 'oppure importa da file CSV', 'plugin_flatpages': 'plugin_flatpages', 'previous 100 rows': '100 righe precedenti', 'readme': 'readme', 'record': 'record', 'record does not exist': 'il record non esiste', 'record id': 'record id', 'register': 'registrazione', 'roadmap': 'roadmap', 'selected': 'selezionato', 'state': 'stato', 'table': 'tabella', 'unable to parse csv file': 'non riesco a decodificare questo file CSV', 'universal cake': 'universal cake', 'voice of access': 'voice of access', }
Python