code
stringlengths
1
1.72M
language
stringclasses
1 value
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def checkEqualRotate(test, nodeName1, nodeName2, precision): test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateX'), MayaCmds.getAttr(nodeName2 + '.rotateX'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateY'), MayaCmds.getAttr(nodeName2 + '.rotateY'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateZ'), MayaCmds.getAttr(nodeName2 + '.rotateZ'), precision) def checkEqualTranslate(test, nodeName1, nodeName2, precision): test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.translateX'), MayaCmds.getAttr(nodeName2 + '.translateX'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.translateY'), MayaCmds.getAttr(nodeName2 + '.translateY'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1+'.translateZ'), MayaCmds.getAttr(nodeName2 + '.translateZ'), precision) def createStaticSolarSystem(): MayaCmds.file(new=True, force=True) moon = MayaCmds.polySphere( radius=0.5, name="moon" )[0] MayaCmds.move( -5, 0.0, 0.0, r=1 ) earth = MayaCmds.polySphere( radius=2, name="earth" )[0] MayaCmds.select( moon, earth ) MayaCmds.group(name='group1') MayaCmds.polySphere( radius=5, name="sun" )[0] MayaCmds.move( 25, 0.0, 0.0, r=1 ) MayaCmds.group(name='group2') def createAnimatedSolarSystem(): MayaCmds.file(new=True, force=True) moon = MayaCmds.polySphere(radius=0.5, name="moon")[0] MayaCmds.move(-5, 0.0, 0.0, r=1) earth = MayaCmds.polySphere(radius=2, name="earth")[0] MayaCmds.select(moon, earth) MayaCmds.group(name='group1') MayaCmds.polySphere(radius=5, name="sun")[0] MayaCmds.move(25, 0.0, 0.0, r=1) MayaCmds.group(name='group2') # the sun's simplified self-rotation MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('sun', at='rotateY', v=0) MayaCmds.currentTime(240, update=True) MayaCmds.setKeyframe('sun', at='rotateY', v=360) # the earth rotate around the sun MayaCmds.expression( s='$angle = (frame-91)/180*3.1415;\n\ earth.translateX = 25+25*sin($angle)') MayaCmds.expression( s='$angle = (frame-91)/180*3.1415;\n\ earth.translateZ = 25*cos($angle)') # the moon rotate around the earth MayaCmds.expression( s='$angle = (frame-91)/180*3.1415+frame;\n\ moon.translateX = earth.translateX+5*sin($angle)') MayaCmds.expression( s='$angle = (frame-91)/180*3.1415+frame;\n\ moon.translateZ = earth.translateZ+5*cos($angle)') class AbcImportSwapTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] # write out an animated Alembic file createAnimatedSolarSystem() self.__files.append(util.expandFileName('testAnimatedSolarSystem.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root group1 -root group2 -file ' + self.__files[-1]) # write out a static Alembic file that's different than the static scene # created by createStaticSolarSystem() MayaCmds.currentTime(12, update=True) self.__files.append(util.expandFileName('testStaticSolarSystem.abc')) MayaCmds.AbcExport(j='-fr 12 12 -root group1 -root group2 -file ' + self.__files[-1]) # write out an animated mesh with animated parent transform node MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') # key the transform node MayaCmds.setKeyframe('group', attribute='translate', t=[1, 4]) MayaCmds.move(0.36, 0.72, 0.36) MayaCmds.setKeyframe('group', attribute='translate', t=2) #key the mesh node MayaCmds.select('polyMesh.vtx[0:8]') MayaCmds.setKeyframe(t=[1, 4]) MayaCmds.scale(0.1, 0.1, 0.1, r=True) MayaCmds.setKeyframe(t=2) self.__files.append(util.expandFileName('testAnimatedMesh.abc')) MayaCmds.AbcExport(j='-fr 1 4 -root group -file ' + self.__files[-1]) MayaCmds.file(new=True, force=True) def tearDown(self): for f in self.__files : os.remove(f) def testStaticSceneSwapInStaticAlembicTransform(self): createStaticSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='/', debug=False ) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testStaticSceneSwapInAnimatedAbcTransform(self): createStaticSolarSystem() # swap in the animated hierarchy MayaCmds.AbcImport(self.__files[0], connect='/', debug=False) # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[0], mode='import') # check the swapped scene at every frame for frame in range(1, 25): MayaCmds.currentTime(frame, update=True) # tranform node moon checkEqualTranslate(self, 'group1|moon', 'group3|moon', 4) # transform node earth checkEqualTranslate(self, 'group1|earth', 'group3|earth', 4) # transform node sun checkEqualRotate(self, 'group2|sun', 'group4|sun', 4) def testAnimatedSceneSwapInStaticAbcTransform(self): createAnimatedSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='/') # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testRemoveIfNoUpdate(self): createStaticSolarSystem() # add a few nodes that don't exist in the Alembic file MayaCmds.createNode('transform', name='saturn') MayaCmds.parent('saturn', 'group1') MayaCmds.createNode('transform', name='venus') MayaCmds.parent('venus', 'group2') MayaCmds.AbcImport(self.__files[1], connect='/', removeIfNoUpdate=True) # check if venus and saturn is deleted self.failUnlessEqual(MayaCmds.objExists('venus'), False) self.failUnlessEqual(MayaCmds.objExists('saturn'), False) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testCreateIfNotFound(self): createStaticSolarSystem() # delete some nodes MayaCmds.delete( 'sunShape' ) MayaCmds.delete( 'moon' ) MayaCmds.AbcImport(self.__files[1], connect='/', createIfNotFound=True) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testPartialSwap(self): createStaticSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='group1', createIfNotFound=True) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testAnimatedMeshSwap(self): MayaCmds.polyPlane( sx=2, sy=2, w=1, h=1, ch=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') MayaCmds.AbcImport(self.__files[2], connect='group') # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[2], mode='import') # check the swapped scene at every frame for frame in range(1, 4): MayaCmds.currentTime(frame, update=True) # tranform node group checkEqualTranslate(self, 'group', 'group1', 4) # tranform node group checkEqualTranslate(self, 'group|polyMesh', 'group1|polyMesh', 4) # mesh node polyMesh for index in range(0, 9): string1 = 'group|polyMesh.vt[%d]' % index string2 = 'group1|polyMesh.vt[%d]' % index self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][0], MayaCmds.getAttr(string2)[0][0], 4, '%s.x != %s.x' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][1], MayaCmds.getAttr(string2)[0][1], 4, '%s.y != %s.y' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][2], MayaCmds.getAttr(string2)[0][2], 4, '%s.z != %s.z' % (string1, string2)) def testMeshTopoChange(self): MayaCmds.polySphere( sx=10, sy=15, r=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') MayaCmds.AbcImport(self.__files[2], connect='group') # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[2], mode='import') # check the swapped scene at every frame for frame in range(1, 4): MayaCmds.currentTime(frame, update=True) # tranform node group checkEqualTranslate(self, 'group', 'group1', 4) # tranform node group checkEqualTranslate(self, 'group|polyMesh', 'group1|polyMesh', 4) # mesh node polyMesh for index in range(0, 9): string1 = 'group|polyMesh.vt[%d]' % index string2 = 'group1|polyMesh.vt[%d]' % index self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][0], MayaCmds.getAttr(string2)[0][0], 4, '%s.x != %s.x' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][1], MayaCmds.getAttr(string2)[0][1], 4, '%s.y != %s.y' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][2], MayaCmds.getAttr(string2)[0][2], 4, '%s.z != %s.z' % (string1, string2))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import math # adds the current working directory so tools don't get confused about where we # are storing files def expandFileName(name): return os.getcwd() + os.path.sep + name # compare the two floating point values def floatDiff(val1, val2, tolerance): diff = math.fabs(val1 - val2) if diff < math.pow(10, -tolerance): return True return False # function that returns a node object given a name def getObjFromName(nodeName): selectionList = OpenMaya.MSelectionList() selectionList.add( nodeName ) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj # function that finds a plug given a node object and plug name def getPlugFromName(attrName, nodeObj): fnDepNode = OpenMaya.MFnDependencyNode(nodeObj) attrObj = fnDepNode.attribute(attrName) plug = OpenMaya.MPlug(nodeObj, attrObj) return plug # meaning of return value: # 0 if array1 = array2 # 1 if array1 and array2 are of the same length, array1[i] == array2[i] for 0<=i<m<len, and array1[m] < array2[m] # -1 if array1 and array2 are of the same length, array1[i] == array2[i] for 0<=i<m<len, and array1[m] > array2[m] # 2 if array1.length() < array2.length() # -2 if array1.length() > array2.length() def compareArray(array1, array2): len1 = array1.length() len2 = array2.length() if len1 > len2 : return -2 if len1 < len2 : return 2 for i in range(0, len1): if array1[i] < array2[i] : return 1 if array1[i] > array2[i] : return -1 return 0 # return True if the two point arrays are exactly the same def comparePointArray(array1, array2): len1 = array1.length() len2 = array2.length() if len1 != len2 : return False for i in range(0, len1): if array1[i] != array2[i]: return False return True # return True if the two meshes are identical def compareMesh( nodeName1, nodeName2 ): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kMesh): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kMesh): return False polyIt1 = OpenMaya.MItMeshPolygon( obj1 ) polyIt2 = OpenMaya.MItMeshPolygon( obj2 ) if polyIt1.count() != polyIt2.count(): return False if polyIt1.polygonVertexCount() != polyIt2.polygonVertexCount(): return False vertices1 = OpenMaya.MIntArray() vertices2 = OpenMaya.MIntArray() pointArray1 = OpenMaya.MPointArray() pointArray2 = OpenMaya.MPointArray() while polyIt1.isDone()==False and polyIt2.isDone()==False : # compare vertex indices polyIt1.getVertices(vertices1) polyIt2.getVertices(vertices2) if compareArray(vertices1, vertices2) != 0: return False # compare vertex positions polyIt1.getPoints(pointArray1) polyIt2.getPoints(pointArray2) if not comparePointArray( pointArray1, pointArray2 ): return False polyIt1.next() polyIt2.next() if polyIt1.isDone() and polyIt2.isDone() : return True return False # return True if the two Nurbs Surfaces are identical def compareNurbsSurface(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kNurbsSurface): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kNurbsSurface): return False fn1 = OpenMaya.MFnNurbsSurface(obj1) fn2 = OpenMaya.MFnNurbsSurface(obj2) # degree if fn1.degreeU() != fn2.degreeU(): return False if fn1.degreeV() != fn2.degreeV(): return False # span if fn1.numSpansInU() != fn2.numSpansInU(): return False if fn1.numSpansInV() != fn2.numSpansInV(): return False # form if fn1.formInU() != fn2.formInU(): return False if fn1.formInV() != fn2.formInV(): return False # control points if fn1.numCVsInU() != fn2.numCVsInU(): return False if fn1.numCVsInV() != fn2.numCVsInV(): return False cv1 = OpenMaya.MPointArray() fn1.getCVs(cv1) cv2 = OpenMaya.MPointArray() fn2.getCVs(cv2) if not comparePointArray(cv1, cv2): return False # knots if fn1.numKnotsInU() != fn2.numKnotsInU(): return False if fn1.numKnotsInV() != fn2.numKnotsInV(): return False knotsU1 = OpenMaya.MDoubleArray() fn1.getKnotsInU(knotsU1) knotsV1 = OpenMaya.MDoubleArray() fn1.getKnotsInV(knotsV1) knotsU2 = OpenMaya.MDoubleArray() fn2.getKnotsInU(knotsU2) knotsV2 = OpenMaya.MDoubleArray() fn2.getKnotsInV(knotsV2) if compareArray( knotsU1, knotsU2 ) != 0: return False if compareArray( knotsV1, knotsV2 ) != 0: return False # trim curves if fn1.isTrimmedSurface() != fn2.isTrimmedSurface(): return False # may need to add more trim checks return True # return True if the two locators are idential def compareLocator(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kLocator): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kLocator): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionX'), MayaCmds.getAttr(nodeName2+'.localPositionX'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionY'), MayaCmds.getAttr(nodeName2+'.localPositionY'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionZ'), MayaCmds.getAttr(nodeName2+'.localPositionZ'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleX'), MayaCmds.getAttr(nodeName2+'.localScaleX'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleY'), MayaCmds.getAttr(nodeName2+'.localScaleY'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleZ'), MayaCmds.getAttr(nodeName2+'.localScaleZ'), 4): return False return True # return True if the two cameras are identical def compareCamera( nodeName1, nodeName2 ): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kCamera): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kCamera): return False fn1 = OpenMaya.MFnCamera( obj1 ) fn2 = OpenMaya.MFnCamera( obj2 ) if fn1.filmFit() != fn2.filmFit(): print "differ in filmFit" return False if not floatDiff(fn1.filmFitOffset(), fn2.filmFitOffset(), 4): print "differ in filmFitOffset" return False if fn1.isOrtho() != fn2.isOrtho(): print "differ in isOrtho" return False if not floatDiff(fn1.orthoWidth(), fn2.orthoWidth(), 4): print "differ in orthoWidth" return False if not floatDiff(fn1.focalLength(), fn2.focalLength(), 4): print "differ in focalLength" return False if not floatDiff(fn1.lensSqueezeRatio(), fn2.lensSqueezeRatio(), 4): print "differ in lensSqueezeRatio" return False if not floatDiff(fn1.cameraScale(), fn2.cameraScale(), 4): print "differ in cameraScale" return False if not floatDiff(fn1.horizontalFilmAperture(), fn2.horizontalFilmAperture(), 4): print "differ in horizontalFilmAperture" return False if not floatDiff(fn1.verticalFilmAperture(), fn2.verticalFilmAperture(), 4): print "differ in verticalFilmAperture" return False if not floatDiff(fn1.horizontalFilmOffset(), fn2.horizontalFilmOffset(), 4): print "differ in horizontalFilmOffset" return False if not floatDiff(fn1.verticalFilmOffset(), fn2.verticalFilmOffset(), 4): print "differ in verticalFilmOffset" return False if not floatDiff(fn1.overscan(), fn2.overscan(), 4): print "differ in overscan" return False if not floatDiff(fn1.nearClippingPlane(), fn2.nearClippingPlane(), 4): print "differ in nearClippingPlane" return False if not floatDiff(fn1.farClippingPlane(), fn2.farClippingPlane(), 4): print "differ in farClippingPlane" return False if not floatDiff(fn1.preScale(), fn2.preScale(), 4): print "differ in preScale" return False if not floatDiff(fn1.postScale(), fn2.postScale(), 4): print "differ in postScale" return False if not floatDiff(fn1.filmTranslateH(), fn2.filmTranslateH(), 4): print "differ in filmTranslateH" return False if not floatDiff(fn1.filmTranslateV(), fn2.filmTranslateV(), 4): print "differ in filmTranslateV" return False if not floatDiff(fn1.horizontalRollPivot(), fn2.horizontalRollPivot(), 4): print "differ in horizontalRollPivot" return False if not floatDiff(fn1.verticalRollPivot(), fn2.verticalRollPivot(), 4): print "differ in verticalRollPivot" return False if fn1.filmRollOrder() != fn2.filmRollOrder(): print "differ in filmRollOrder" return False if not floatDiff(fn1.filmRollValue(), fn2.filmRollValue(), 4): print "differ in filmRollValue" return False if not floatDiff(fn1.fStop(), fn2.fStop(), 4): print "differ in fStop" return False if not floatDiff(fn1.focusDistance(), fn2.focusDistance(), 4,): print "differ in focusDistance" return False if not floatDiff(fn1.shutterAngle(), fn2.shutterAngle(), 4): print "differ in shutterAngle" return False if fn1.usePivotAsLocalSpace() != fn2.usePivotAsLocalSpace(): print "differ in usePivotAsLocalSpace" return False if fn1.tumblePivot() != fn2.tumblePivot(): print "differ in tumblePivot" return False return True # return True if the two Nurbs curves are identical def compareNurbsCurve(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kNurbsCurve): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kNurbsCurve): return False fn1 = OpenMaya.MFnNurbsCurve(obj1) fn2 = OpenMaya.MFnNurbsCurve(obj2) if fn1.form() != fn2.form(): return False if fn1.degree() != fn2.degree(): return False if fn1.numCVs() != fn2.numCVs(): return False if fn1.numSpans() != fn2.numSpans(): return False if fn1.numKnots() != fn2.numKnots(): return False cv1 = OpenMaya.MPointArray() fn1.getCVs(cv1) cv2 = OpenMaya.MPointArray() fn2.getCVs(cv2) if not comparePointArray(cv1, cv2): return False knots1 = OpenMaya.MDoubleArray() fn1.getKnots(knots1) knots2 = OpenMaya.MDoubleArray() fn2.getKnots(knots2) if compareArray(knots1, knots2) != 0: return False return True
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class subframesTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testRangeFlag(self): MayaCmds.createNode('transform', name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=11.0, v=11.0) self.__files.append(util.expandFileName('rangeTest.abc')) MayaCmds.AbcExport(j='-fr 1 11 -step 0.25 -root node -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.currentTime(0, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1.0003, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1.333333, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.translateX'), 1.333333333, 2) MayaCmds.currentTime(9.66667, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.translateX'), 9.6666666666, 2) MayaCmds.currentTime(11, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 11) MayaCmds.currentTime(12, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 11) def testPreRollStartFrameFlag(self): MayaCmds.createNode('transform', name='node') MayaCmds.setAttr('node.tx', 0.0) MayaCmds.expression( string="if(time==0)\n\tnode.tx=0;\n\nif (time*24 > 6 && node.tx > 0.8)\n\tnode.tx = 10;\n\nnode.tx = node.tx + time;\n", name="startAtExp", ae=1, uc=all) self.__files.append(util.expandFileName('startAtTest.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root node -file ' + self.__files[-1], prs=0, duf=True) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # if the evaluation doesn't start at frame 0, node.tx < 10 MayaCmds.currentTime(10, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnless(MayaCmds.getAttr('node.translateX')-10 > 0) def testSkipFrames(self): MayaCmds.createNode('transform', name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=10.0, v=10.0) MayaCmds.duplicate(name='dupNode') MayaCmds.setAttr('dupNode.tx', 0.0) MayaCmds.expression( string="if(time==11)\n\tdupNode.tx=-50;\n\ndupNode.tx = dupNode.tx + time;\n", name="startAtExp", ae=1, uc=all) self.__files.append(util.expandFileName('skipFrameTest1.abc')) self.__files.append(util.expandFileName('skipFrameTest2.abc')) MayaCmds.AbcExport(j=['-fr 1 10 -root node -file ' + self.__files[-2], '-fr 20 25 -root dupNode -file ' + self.__files[-1]]) MayaCmds.AbcImport(self.__files[-2], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # make sure all the frames needed are written out and correctly for val in range(1, 11): MayaCmds.currentTime(val, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.tx'), val, 3) # also make sure nothing extra gets written out MayaCmds.currentTime(11, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.tx'), 10.0) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # if dontSkipFrames flag is not set maya would evaluate frame 11 and # set dupNode.tx to a big negative number MayaCmds.currentTime(20, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnless(MayaCmds.getAttr('dupNode.tx') > 0) def testWholeFrameGeoFlag(self): MayaCmds.polyCube(name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=2.0, v=-3.0) MayaCmds.setKeyframe('node.translateX', time=5.0, v=9.0) MayaCmds.select('node.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('noSampleGeoTest.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -frs 0 -frs 0.9 -root node -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') setTime = MayaCmds.currentTime(1, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) val_1 = MayaCmds.getAttr('node.vt[0]')[0][0] MayaCmds.currentTime(2.0, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) MayaCmds.getAttr('node.vt[0]') val_2 = MayaCmds.getAttr('node.vt[0]')[0][0] self.failUnlessAlmostEqual(val_2, -0.5625, 3) setTime = MayaCmds.currentTime(1.9, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.tx'), -3.086, 3) # the vertex will get linearly interpolated alpha = (setTime - 1) / (2 - 1) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.vt[0]')[0][0], (1-alpha)*val_1+alpha*val_2, 3) # convenience functions for the tests following def noFrameRangeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal != 0) def isFrameRangeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=2.time', fileName]) self.failUnless(retVal != 0) retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal == 0) def isFrameRangeTransAndFrameRangeShapeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=2.time', fileName]) self.failUnless(retVal == 0) retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal == 0) def test_agat(self): # animated geometry, animated transform node nodename = 'agat_node' MayaCmds.polyCube(name=nodename) MayaCmds.setKeyframe(nodename+'.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe(nodename+'.translateX', time=5.0, v=10.0) MayaCmds.select(nodename+'.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('agat_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -step 0.5 -root %s -file %s' % ( nodename, self.__files[-1])) # frameRangeShape: 1, 2, 3, 4, 5, 6 # frameRangeTrans: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('agat_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) self.__files.append(util.expandFileName('agat_norange_Test.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (nodename,self.__files[-1])) # no frameRange self.noFrameRangeExists(self.__files[-1]) def test_agst(self): # animated geometry, static transform node nodename = 'agst_node' MayaCmds.polyCube(name=nodename) MayaCmds.select(nodename+'.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('agst_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: 1, 2, 3, 4, 5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('agst_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -f %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) self.__files.append(util.expandFileName('agst_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -root %s -f %s' % (nodename, self.__files[-1])) # frameRange: 1, 2, 3, 4, 5 self.isFrameRangeExists(self.__files[-1]) def test_sgat(self): # static geometry, animated transform node nodename = 'sgat_node' MayaCmds.polyCube(name=nodename) MayaCmds.setKeyframe(nodename+'.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe(nodename+'.translateX', time=5.0, v=10.0) self.__files.append(util.expandFileName('sgat_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -f %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('sgat_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -f %s ' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) def test_sgst(self): # static geometry, static transform node nodename = 'sgst_node' MayaCmds.polyCube(name=nodename) self.__files.append(util.expandFileName('sgst_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -file %s ' % ( nodename, self.__files[-1])) self.failIf(MayaCmds.AbcImport(self.__files[-1]) != "") self.__files.append(util.expandFileName('sgst_moblur_noSampleGeo_norange_Test.abc')) MayaCmds.AbcExport(j='-step 0.5 -wfg -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: NA self.noFrameRangeExists(self.__files[-1])
Python
# # Copyright (c) 2010 Sony Pictures Imageworks Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the # distribution. Neither the name of Sony Pictures Imageworks nor the # names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. from maya import cmds as MayaCmds from maya import mel as Mel import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") def makeRobotAnimated(): makeRobot() #change pivot point of arms and legs MayaCmds.move(0.65, -0.40, 0, 'rightArm.scalePivot', 'rightArm.rotatePivot', relative=True) MayaCmds.move(-0.65, -0.40, 0, 'leftArm.scalePivot', 'leftArm.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'rightLeg.scalePivot', 'rightLeg.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'leftLeg.scalePivot', 'leftLeg.rotatePivot', relative=True) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=25, t=[1, 12]) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=-40, t=[6]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=2.8, t=[1, 12]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=5.0, t=[6]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=55, t=[1, 12]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=-50, t=[6]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=0.5, t=[1, 12]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=3.6, t=[6]) class AbcNodeNameTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testReturnAbcNodeName(self): makeRobotAnimated() self.__files.append(util.expandFileName('returnAlembicNodeNameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -root robot -file ' + self.__files[-1]) ret = MayaCmds.AbcImport(self.__files[-1], mode='open') ret1 = MayaCmds.AbcImport(self.__files[-1], mode='import') self.failUnless(MayaCmds.objExists(ret)) self.failUnless(MayaCmds.objExists(ret1)) self.failIf(ret == ret1)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class staticPropTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def setProps(self, nodeName): MayaCmds.select(nodeName) MayaCmds.addAttr(longName='SPT_int8', defaultValue=8, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=16, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=32, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=3.2654, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=0.15724757, attributeType='double', keyable=True) MayaCmds.addAttr(longName='SPT_double_AbcGeomScope', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_double_AbcGeomScope', "vtx", type="string") MayaCmds.addAttr(longName='SPT_string', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_string', "empty", type="string") MayaCmds.addAttr(longName='SPT_string_AbcGeomScope', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_string_AbcGeomScope', "potato", type="string") MayaCmds.addAttr(longName='SPT_int32_array', dataType='Int32Array') MayaCmds.setAttr(nodeName+'.SPT_int32_array', [6, 7, 8, 9, 10], type='Int32Array') MayaCmds.addAttr(longName='SPT_vector_array', dataType='vectorArray') MayaCmds.setAttr(nodeName+'.SPT_vector_array', 3, (1,1,1), (2,2,2), (3,3,3), type='vectorArray') MayaCmds.addAttr(longName='SPT_vector_array_AbcType', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_vector_array_AbcType', "normal2", type="string") MayaCmds.addAttr(longName='SPT_point_array', dataType='pointArray') MayaCmds.setAttr(nodeName+'.SPT_point_array', 2, (2,4,6,8), (20,40,60,80), type='pointArray') MayaCmds.addAttr(longName='SPT_double_array', dataType='doubleArray') MayaCmds.addAttr(longName='SPT_double_array_AbcGeomScope', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_double_array', [1.1, 2.2, 3.3, 4.4, 5.5], type='doubleArray') MayaCmds.setAttr(nodeName+'.SPT_double_array_AbcGeomScope', "vtx", type="string") MayaCmds.addAttr(longName='SPT_string_array', dataType='stringArray') MayaCmds.setAttr(nodeName+'.SPT_string_array', 3, "string1", "string2", "string3", type='stringArray') def verifyProps(self, nodeName, fileName): MayaCmds.AbcImport(fileName, mode='open') self.failUnlessEqual(8, MayaCmds.getAttr(nodeName+'.SPT_int8')) self.failUnlessEqual(16, MayaCmds.getAttr(nodeName+'.SPT_int16')) self.failUnlessEqual(32, MayaCmds.getAttr(nodeName+'.SPT_int32')) self.failUnlessAlmostEqual(3.2654, MayaCmds.getAttr(nodeName+'.SPT_float'), 4) self.failUnlessAlmostEqual(0.15724757, MayaCmds.getAttr(nodeName+'.SPT_double'), 7) self.failUnlessEqual('vtx', MayaCmds.getAttr(nodeName+'.SPT_double_AbcGeomScope')) self.failUnlessEqual('empty', MayaCmds.getAttr(nodeName+'.SPT_string')) self.failUnlessEqual(0, MayaCmds.attributeQuery( 'SPT_string_AbcGeomScope', node=nodeName, exists=True)) self.failUnlessEqual([6, 7, 8, 9, 10], MayaCmds.getAttr(nodeName+'.SPT_int32_array')) self.failUnlessEqual(["string1", "string2", "string3"], MayaCmds.getAttr(nodeName+'.SPT_string_array')) self.failUnlessEqual([1.1, 2.2, 3.3, 4.4, 5.5], MayaCmds.getAttr(nodeName+'.SPT_double_array')) self.failUnlessEqual([(1.0, 1.0, 0.0), (2.0, 2.0, 0.0), (3.0, 3.0, 0.0)], MayaCmds.getAttr(nodeName+'.SPT_vector_array')) self.failUnlessEqual('normal2', MayaCmds.getAttr(nodeName+'.SPT_vector_array_AbcType')) self.failUnlessEqual([(2.0, 4.0, 6.0, 1.0), (20.0, 40.0, 60.0, 1.0)], MayaCmds.getAttr(nodeName+'.SPT_point_array')) def testStaticTransformPropReadWrite(self): nodeName = MayaCmds.createNode('transform') self.setProps(nodeName) self.__files.append(util.expandFileName('staticPropTransform.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -file %s' % (nodeName, self.__files[-1])) self.verifyProps(nodeName, self.__files[-1]) def testStaticCameraPropReadWrite(self): root = MayaCmds.camera() nodeName = root[0] shapeName = root[1] self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropCamera.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticParticlePropReadWrite(self): root = MayaCmds.particle(p=[(0, 0, 0), (1, 1, 1)]) nodeName = root[0] shapeName = root[1] self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropParticles.abc')) MayaCmds.AbcExport(j='-atp -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticMeshPropReadWrite(self): nodeName = 'polyCube' shapeName = 'polyCubeShape' MayaCmds.polyCube(name=nodeName) self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropMesh.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticNurbsCurvePropReadWrite(self): nodeName = 'nCurve' shapeName = 'curveShape1' MayaCmds.curve(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)], name=nodeName) self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropCurve.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticNurbsSurfacePropReadWrite(self): nodeName = 'nSphere' shapeName = 'nSphereShape' MayaCmds.sphere(name=nodeName) self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropNurbs.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -file %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def testStaticNurbsWithoutTrim(self, surfacetype, abcFileName): if (surfacetype == 0): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) errmsg = 'Nurbs Plane' elif (surfacetype == 1): ret = MayaCmds.sphere(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, r=1, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0) errmsg = 'Nurbs Sphere' elif (surfacetype == 2): ret = MayaCmds.torus(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, msw=360, r=1, hr=0.5, ch=0) errmsg = 'Nurbs Torus' name = ret[0] degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints = MayaCmds.getAttr(surfaceInfoNode+'.controlPoints[*]') knotsU = MayaCmds.getAttr(surfaceInfoNode+'.knotsU[*]') knotsV = MayaCmds.getAttr(surfaceInfoNode+'.knotsV[*]') MayaCmds.AbcExport(j='-root %s -f %s' % (name, abcFileName)) # reading test MayaCmds.AbcImport(abcFileName, mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) # form will always be open self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formV')) surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints2 = MayaCmds.getAttr(surfaceInfoNode + '.controlPoints[*]') self.failUnlessEqual(len(controlPoints), len(controlPoints2)) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = controlPoints2[i] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'cp[%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'cp[%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'cp[%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i) def testStaticNurbsWithOneCloseCurveTrim(self, surfacetype, abcFileName, trimtype): if (surfacetype == 0): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) elif (surfacetype == 1): ret = MayaCmds.sphere(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, r=1, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0) elif (surfacetype == 2): ret = MayaCmds.torus(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, msw=360, r=1, hr=0.5, ch=0) name = ret[0] MayaCmds.curveOnSurface(name, uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296), (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)), k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957)) MayaCmds.closeCurve(name+'->curve1', ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1) if trimtype == 0 : MayaCmds.trim(name, lu=0.68, lv=0.39) elif 1 : MayaCmds.trim(name, lu=0.267062, lv=0.39475) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') formU = MayaCmds.getAttr(name+'.formU') formV = MayaCmds.getAttr(name+'.formV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints = MayaCmds.getAttr(surfaceInfoNode+'.controlPoints[*]') knotsU = MayaCmds.getAttr(surfaceInfoNode+'.knotsU[*]') knotsV = MayaCmds.getAttr(surfaceInfoNode+'.knotsV[*]') MayaCmds.AbcExport(j='-root %s -f %s' % (name, abcFileName)) MayaCmds.AbcImport(abcFileName, mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints2 = MayaCmds.getAttr( surfaceInfoNode + '.controlPoints[*]') self.failUnlessEqual(len(controlPoints), len(controlPoints2)) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = controlPoints2[i] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'cp[%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'cp[%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'cp[%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i) class StaticNurbsSurfaceTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticNurbsSurfaceWithoutTrimReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 0, self.__files[-1]) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 1, self.__files[-1]) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 2 , self.__files[-1]) def testStaticNurbsSurfaceWithOneCloseCurveTrimInsideReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 0 , self.__files[-1], 0) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 1, self.__files[-1], 0) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 2, self.__files[-1], 0) def testStaticNurbsSurfaceWithOneCloseCurveTrimOutsideReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 0, self.__files[-1], 1) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 1, self.__files[-1], 1) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 2, self.__files[-1], 1) def testStaticNurbsPlaneWithOneSegmentTrimReadWrite(self): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) name = ret[0] MayaCmds.curveOnSurface(name, uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218), (0.496932,0.779936), (0.672153,1)), k=(0,0,0,0.263463,0.530094,0.530094,0.530094)) MayaCmds.trim(name, lu=0.68, lv=0.39) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneSegmentTrim.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % i) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, 'control point [%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, 'control point [%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, 'control point [%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class MayaReloadTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # this test makes sure that not just the vertex positions but the # connection info is all correct def testAnimMeshReload(self): MayaCmds.polyCube( name = 'mesh') MayaCmds.setKeyframe('meshShape.vtx[0:7]', time=[1, 24]) MayaCmds.setKeyframe('meshShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) MayaCmds.select('meshShape.vtx[0:7]') MayaCmds.scale(5, 5, 5, r=True) MayaCmds.setKeyframe('meshShape.vtx[0:7]', time=[12]) self.__files.append(util.expandFileName('testAnimMeshReadWrite.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root mesh -f ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # save as a maya file self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # reload as a maya file MayaCmds.file(self.__files[-1], open=True) MayaCmds.AbcImport(self.__files[-2], mode='import') retVal = True mesh1 = '|mesh|meshShape' mesh2 = '|mesh1|meshShape' for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh( mesh1, mesh2 ): self.fail('%s and %s were not equal at frame %d' % (mesh1, mesh2, t)) #------------------------------------------------------------------------------- # The following tests each creates four animated nodes of the same data # type, writes out to Abc file, loads back the file and deletes one node. # Then the scene is saved as a Maya file, and load back to check if the # reload works as expected #------------------------------------------------------------------------------- def testAnimPolyDeleteReload(self): # create a poly cube and animate shapeName = 'pCube' MayaCmds.polyCube( name=shapeName ) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[2:5]', time=[1, 24] ) MayaCmds.currentTime( 12 ) MayaCmds.select( shapeName+'.vtx[2:5]',replace=True ) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[2:5]', time=[12] ) # create a poly sphere and animate shapeName = 'pSphere' MayaCmds.polySphere( name=shapeName ) MayaCmds.move(-5, 0, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]',replace=True) MayaCmds.scale(0.5, 0.5, 0.5, relative=True) MayaCmds.setKeyframe( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[12]) MayaCmds.currentTime(1) # create a poly torus and animate shapeName = 'pTorus' MayaCmds.polyTorus(name=shapeName) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]',time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:219]',replace=True) MayaCmds.scale(2, 1, 2, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]', time=[12]) # create a poly cone and animate shapeName = 'pCone' MayaCmds.polyCone(name=shapeName) MayaCmds.move(0, 0, -5, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[20]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[12]) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testPolyReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root pCube -root pSphere -root pTorus -root pCone -file %s' % self.__files[-1]) # load back the Abc file, delete the sphere and save to a maya file MayaCmds.AbcImport( self.__files[-1], mode='open') MayaCmds.delete('pSphere') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('pCube', 'pTorus', 'pCone', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 7) meshes = [('|pCube|pCubeShape', '|ReloadGrp|pCube|pCubeShape'), ('|pTorus|pTorusShape', '|ReloadGrp|pTorus|pTorusShape'), ('|pCone|pConeShape', '|ReloadGrp|pCone|pConeShape')] for m in meshes: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh(m[0], m[1]): self.fail('%s and %s are not the same at frame %d' % (m[0], m[1], t)) def testAnimSubDDeleteReload(self): # create a subD cube and animate shapeName = 'cube' MayaCmds.polyCube( name=shapeName ) MayaCmds.select('cubeShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[2:5]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[12]) # create a subD sphere and animate shapeName = 'sphere' MayaCmds.polySphere(name=shapeName) MayaCmds.select('sphereShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(-5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', replace=True) MayaCmds.scale(0.5, 0.5, 0.5, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[12]) MayaCmds.currentTime(1) # create a subD torus and animate shapeName = 'torus' MayaCmds.polyTorus(name=shapeName) MayaCmds.select('torusShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]',time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:219]',replace=True) MayaCmds.scale(2, 1, 2, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]', time=[12]) # create a subD cone and animate shapeName = 'cone' MayaCmds.polyCone( name=shapeName ) MayaCmds.select('coneShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(0, 0, -5, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[20]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[12]) self.__files.append(util.expandFileName('testSubDReload.abc')) # write it out to Abc file and load back in MayaCmds.AbcExport(j='-fr 1 24 -root cube -root sphere -root torus -root cone -file ' + self.__files[-1]) # load back the Abc file, delete the sphere and save to a maya file MayaCmds.AbcImport( self.__files[-1], mode='open' ) MayaCmds.delete('sphere') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('cube', 'torus', 'cone', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 7) # test the equality of cubes meshes = [('|cube|cubeShape', '|ReloadGrp|cube|cubeShape'), ('|torus|torusShape', '|ReloadGrp|torus|torusShape'), ('|cone|coneShape', '|ReloadGrp|cone|coneShape')] for m in meshes: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh(m[0], m[1]): self.fail('%s and %s are not the same at frame %d' % (m[0], m[1], t)) def testAnimNSurfaceDeleteReload(self): # create an animated Nurbs sphere MayaCmds.sphere(ch=False, name='nSphere') MayaCmds.move(5, 0, 0, relative=True) MayaCmds.select('nSphere.cv[0:1][0:7]', 'nSphere.cv[5:6][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.scale(1.5, 1, 1, relative=True) MayaCmds.setKeyframe(time=12) # create an animated Nurbs torus MayaCmds.torus(ch=False, name='nTorus') MayaCmds.move(-5, 0, 0, relative=True) MayaCmds.select('nTorus.cv[0][0:7]', 'nTorus.cv[2][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.scale(1, 2, 2, relative=True) MayaCmds.setKeyframe(time=12) # create an animated Nurbs plane # should add the trim curve test on this surface, will be easier # than the rest MayaCmds.nurbsPlane(ch=False, name='nPlane') MayaCmds.move(-5, 5, 0, relative=True) MayaCmds.select('nPlane.cv[0:3][0:3]', replace=True) MayaCmds.setKeyframe(time=1) MayaCmds.currentTime(12, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=12) MayaCmds.currentTime(24, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=24) # create an animated Nurbs cylinder MayaCmds.cylinder(ch=False, name='nCylinder') MayaCmds.select('nCylinder.cv[0][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.move(-3, 0, 0, relative=True) MayaCmds.setKeyframe(time=12) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testNSurfaceReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root nSphere -root nTorus -root nPlane -root nCylinder -file ' + self.__files[-1]) # load back the Abc file, delete the torus and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('nTorus') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('nSphere', 'nPlane', 'nCylinder', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') surfaceList = MayaCmds.ls(type='nurbsSurface') self.failUnlessEqual(len(surfaceList), 7) surfaces = [('|nSphere|nSphereShape', '|ReloadGrp|nSphere|nSphereShape'), ('|nPlane|nPlaneShape', '|ReloadGrp|nPlane|nPlaneShape'), ('|nCylinder|nCylinderShape', '|ReloadGrp|nCylinder|nCylinderShape')] for s in surfaces: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsSurface(s[0], s[1]): self.fail('%s and %s are not the same at frame %d' % (s[0], s[1], t)) def testAnimNSurfaceAndPolyDeleteReload(self): # create a poly cube and animate shapeName = 'pCube' MayaCmds.polyCube(name=shapeName) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[2:5]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[12]) # create an animated Nurbs plane MayaCmds.nurbsPlane(ch=False, name='nPlane') MayaCmds.move(-5, 5, 0, relative=True) MayaCmds.select('nPlane.cv[0:3][0:3]', replace=True) MayaCmds.setKeyframe(time=1) MayaCmds.currentTime(12, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=12) MayaCmds.currentTime(24, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=24) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testNSurfaceAndPolyReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root pCube -root nPlane -file ' + self.__files[-1]) # load back the Abc file, delete the cube and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('pCube') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('nPlane', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 1) surfaceList = MayaCmds.ls(type='nurbsSurface') self.failUnlessEqual(len(surfaceList), 2) # test the equality of plane surface1 = '|nPlane|nPlaneShape' surface2 = '|ReloadGrp|nPlane|nPlaneShape' for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsSurface( surface1, surface2 ): self.fail('%s and %s are not the same at frame %d' % (surface1, surface2, t)) def testAnimCameraDeleteReload(self): # cam1 MayaCmds.camera(name='cam1') MayaCmds.setAttr('cam1Shape1.horizontalFilmAperture', 0.962) MayaCmds.setAttr('cam1Shape1.verticalFilmAperture', 0.731) MayaCmds.setAttr('cam1Shape1.focalLength', 50) MayaCmds.setAttr('cam1Shape1.focusDistance', 5) MayaCmds.setAttr('cam1Shape1.shutterAngle', 144) MayaCmds.setAttr('cam1Shape1.centerOfInterest', 1384.825) # cam2 MayaCmds.duplicate('cam1', returnRootsOnly=True) # cam3 MayaCmds.duplicate('cam1', returnRootsOnly=True) # cam4 MayaCmds.duplicate('cam1', returnRootsOnly=True) # animate each camera slightly different MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('cam1Shape1', attribute='horizontalFilmAperture') MayaCmds.setKeyframe('cam2Shape', attribute='focalLength') MayaCmds.setKeyframe('cam3Shape', attribute='focusDistance') MayaCmds.setKeyframe('cam4Shape', attribute='shutterAngle') MayaCmds.setKeyframe('cam4Shape', attribute='centerOfInterest') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('cam1Shape1', attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe('cam2Shape', attribute='focalLength', value=40) MayaCmds.setKeyframe('cam3Shape', attribute='focusDistance', value=5.4) MayaCmds.setKeyframe('cam4Shape', attribute='shutterAngle', value=174.94) MayaCmds.setKeyframe('cam4Shape', attribute='centerOfInterest', value=67.418) # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testCamReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root cam1 -root cam2 -root cam3 -root cam4 -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd camera and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('cam2') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('cam1', 'cam3', 'cam4', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') camList = MayaCmds.ls(type='camera') # should be 7, but this query will return the four standard cameras in # the scene too self.failUnlessEqual(len(camList), 11) # test the equality of cameras cameras = [('|cam1|cam1Shape1', '|ReloadGrp|cam1|cam1Shape1'), ('|cam3|cam3Shape', '|ReloadGrp|cam3|cam3Shape'), ('|cam4|cam4Shape', '|ReloadGrp|cam4|cam4Shape')] for c in cameras: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareCamera(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) def testAnimNCurvesDeleteReload(self): # create some animated curves MayaCmds.textCurves(ch=False, t='Maya', name='Curves', font='Courier') MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:27]', replace=True) MayaCmds.move(-3, 3, 0, relative=True) MayaCmds.select('curve2.cv[0:45]', 'curve3.cv[0:15]', replace=True) MayaCmds.scale(1.5, 1.5, 1.5, relative=True) MayaCmds.select('curve4.cv[0:19]', replace=True) MayaCmds.move(1.5, 0, 0, relative=True) MayaCmds.rotate(0, 90, 0, relative=True) MayaCmds.select('curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.move(3, 0, 0, relative=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testNCurvesReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root CurvesShape -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') # delete letter "a" which has two curves MayaCmds.delete('Char_a_1') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('CurvesShape', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') curveList = MayaCmds.ls(type='nurbsCurve') self.failUnlessEqual(len(curveList), 10) # test the equality of curves curves = [('|CurvesShape|Char_M_1|curve1|curveShape1', '|ReloadGrp|CurvesShape|Char_M_1|curve1|curveShape1'), ('|CurvesShape|Char_y_1|curve4|curveShape4', '|ReloadGrp|CurvesShape|Char_y_1|curve4|curveShape4'), ('|CurvesShape|Char_a_2|curve5|curveShape5', '|ReloadGrp|CurvesShape|Char_a_2|curve5|curveShape5'), ('|CurvesShape|Char_a_2|curve6|curveShape6', '|ReloadGrp|CurvesShape|Char_a_2|curve6|curveShape6')] for c in curves: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsCurve(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) #------------------------------------------------------------------------- def testAnimNCurveGrpDeleteReload(self): # create an animated curves group MayaCmds.textCurves(ch=False, t='haka', name='Curves', font='Courier') MayaCmds.addAttr(longName='riCurves', at='bool', dv=True) MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:27]', replace=True) MayaCmds.move(-3, 3, 0, relative=True) MayaCmds.select('curve2.cv[0:45]', 'curve3.cv[0:15]', replace=True) MayaCmds.scale(1.5, 1.5, 1.5, relative=True) MayaCmds.select('curve4.cv[0:19]', replace=True) MayaCmds.move(1.5, 0, 0, relative=True) MayaCmds.rotate(0, 90, 0, relative=True) MayaCmds.select('curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.move(3, 0, 0, relative=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testNCurveGrpReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root CurvesShape -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') # delete letter "a" which has two curves, but as a curve group. # the curve shapes are renamed under the group node MayaCmds.delete('CurvesShape1') MayaCmds.delete('CurvesShape2') self.__files.append(util.expandFileName('testCurves.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('|CurvesShape', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') curveList = MayaCmds.ls(type='nurbsCurve') self.failUnlessEqual(len(curveList), 10) curves = [('|CurvesShape|CurvesShape', '|ReloadGrp|CurvesShape|CurvesShape'), ('|CurvesShape|CurvesShape8', '|ReloadGrp|CurvesShape|CurvesShape3'), ('|CurvesShape|CurvesShape9', '|ReloadGrp|CurvesShape|CurvesShape4'), ('|CurvesShape|CurvesShape10', '|ReloadGrp|CurvesShape|CurvesShape5')] for c in curves: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsCurve(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) def testAnimPropDeleteReload(self): # create some animated properties on a transform node ( could be any type ) nodeName = MayaCmds.polyPrism(ch=False, name = 'prism') MayaCmds.addAttr(longName='SPT_int8', defaultValue=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=100, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=1000, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=0.57777777, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=5.0456435, attributeType='double', keyable=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(nodeName, attribute='SPT_int8') MayaCmds.setKeyframe(nodeName, attribute='SPT_int16') MayaCmds.setKeyframe(nodeName, attribute='SPT_int32') MayaCmds.setKeyframe(nodeName, attribute='SPT_float') MayaCmds.setKeyframe(nodeName, attribute='SPT_double') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(nodeName, attribute='SPT_int8', value=8) MayaCmds.setKeyframe(nodeName, attribute='SPT_int16', value=16) MayaCmds.setKeyframe(nodeName, attribute='SPT_int32', value=32) MayaCmds.setKeyframe(nodeName, attribute='SPT_float', value=5.24847) MayaCmds.setKeyframe(nodeName, attribute='SPT_double', value=3.14154) # create SPT_HWColor on the shape node MayaCmds.select('prismShape') MayaCmds.addAttr(longName='SPT_HwColorR', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr(longName='SPT_HwColorG', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr(longName='SPT_HwColorB', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr( longName='SPT_HwColor', usedAsColor=True, attributeType='float3') MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(at='SPT_HwColorR') MayaCmds.setKeyframe(at='SPT_HwColorG') MayaCmds.setKeyframe(at='SPT_HwColorB') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(at='SPT_HwColorR', value=0.5) MayaCmds.setKeyframe(at='SPT_HwColorG', value=0.15) MayaCmds.setKeyframe(at='SPT_HwColorB', value=0.75) # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testPropReload.abc')) MayaCmds.AbcExport(j='-atp SPT_ -fr 1 24 -root prism -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file abcNode = MayaCmds.AbcImport( self.__files[-1], mode='open' ) # delete connections to animated props prop = MayaCmds.listConnections('|prism.SPT_float', p=True)[0] MayaCmds.disconnectAttr(prop, '|prism.SPT_float') attr = '|prism|prismShape.SPT_HwColorG' prop = MayaCmds.listConnections(attr, p=True)[0] MayaCmds.disconnectAttr(prop, attr) self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('prism', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') # test the equality of props for t in range(1, 25): MayaCmds.currentTime(t, update=True) self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int8'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int8'), 'prism.SPT_int8 not equal' ) self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int16'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int16'), 'prism.SPT_int16 not equal') self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int32'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int32'), 'prism.SPT_int32 not equal') self.failUnlessAlmostEqual(MayaCmds.getAttr('|prism.SPT_double'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_double'), 4, 'prism.SPT_double not equal') self.failUnlessAlmostEqual( MayaCmds.getAttr('|prism|prismShape.SPT_HwColorR'), MayaCmds.getAttr('|ReloadGrp|prism|prismShape.SPT_HwColorR'), 4, 'prismShape.SPT_HwColorR not equal') self.failUnlessAlmostEqual( MayaCmds.getAttr('|prism|prismShape.SPT_HwColorB'), MayaCmds.getAttr('|ReloadGrp|prism|prismShape.SPT_HwColorB'), 4, 'prismShape.SPT_HwColorB not equal')
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import maya.cmds as MayaCmds import os import subprocess import unittest import util class animPropTest(unittest.TestCase): #------------------------------------------------------------------------- def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [util.expandFileName('animProp.abc'), util.expandFileName('animProp01_14.abc'), util.expandFileName('animProp15_24.abc')] #------------------------------------------------------------------------- def tearDown(self): for f in self.__files : os.remove(f) #------------------------------------------------------------------------- def setAndKeyProps( self, nodeName ): MayaCmds.select(nodeName) MayaCmds.addAttr(longName='SPT_int8', defaultValue=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=0, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=0, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=0, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=0, attributeType='double', keyable=True) MayaCmds.setKeyframe(nodeName, value=0, attribute='SPT_int8', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=100, attribute='SPT_int16', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=1000, attribute='SPT_int32', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0.57777777, attribute='SPT_float', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=5.045643545457, attribute='SPT_double', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=8, attribute='SPT_int8', t=12) MayaCmds.setKeyframe(nodeName, value=16, attribute='SPT_int16', t=12) MayaCmds.setKeyframe(nodeName, value=32, attribute='SPT_int32', t=12) MayaCmds.setKeyframe(nodeName, value=3.141592654, attribute='SPT_float', t=12) MayaCmds.setKeyframe(nodeName, value=3.141592654, attribute='SPT_double', t=12) def verifyProps( self, root, nodeName ): # write to files MayaCmds.AbcExport(j='-atp SPT_ -fr 1 14 -root %s -file %s' % (root, self.__files[1])) MayaCmds.AbcExport(j='-atp SPT_ -fr 15 24 -root %s -file %s' % (root, self.__files[2])) subprocess.call(self.__abcStitcher + self.__files) # read file and verify data MayaCmds.AbcImport(self.__files[0], mode='open') t = 1 # frame 1 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(0, MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 0 at frame %d' %( nodeName, t)) self.failUnlessEqual(100, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 100 at frame %d' %( nodeName, t)) self.failUnlessEqual(1000, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 1000 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(0.57777777, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 0.57777777 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(5.045643545457, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 5.045643545457 at frame %d' %( nodeName, t)) t = 12 # frame 12 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(8, MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 8 at frame %d' %( nodeName, t)) self.failUnlessEqual(16, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 16 at frame %d' %( nodeName, t)) self.failUnlessEqual(32, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 32 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(3.141592654, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 3.141592654 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(3.1415926547, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 3.141592654 at frame %d' %( nodeName, t)) t = 24 # frame 24 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(0,MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 0 at frame %d' % (nodeName, t)) self.failUnlessEqual(100, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 100 at frame %d' % (nodeName, t)) self.failUnlessEqual(1000, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 1000 at frame %d' % (nodeName, t)) self.failUnlessAlmostEqual(0.57777777, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 0.57777777 at frame %d' % (nodeName, t)) self.failUnlessAlmostEqual(5.045643545457, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 5.045643545457 at frame %d' % (nodeName, t)) def testAnimTransformProp(self): nodeName = MayaCmds.createNode('transform') self.setAndKeyProps(nodeName) self.verifyProps(nodeName, nodeName) def testAnimCameraProp(self): root = MayaCmds.camera() nodeName = root[0] shapeName = root[1] self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimMeshProp(self): nodeName = 'polyCube' shapeName = 'polyCubeShape' MayaCmds.polyCube(name=nodeName, ch=False) self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimNurbsCurvePropReadWrite(self): nodeName = 'nCurve' shapeName = 'curveShape1' MayaCmds.curve(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)], name=nodeName) self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimNurbsSurfaceProp(self): nodeName = MayaCmds.sphere(ch=False)[0] nodeNameList = MayaCmds.pickWalk(d='down') shapeName = nodeNameList[0] self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") class selectionTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testWriteMultipleRoots(self): makeRobot() MayaCmds.duplicate("robot", name="dupRobot") self.__files.append(util.expandFileName('writeMultipleRootsTest.abc')) MayaCmds.AbcExport(j='-root dupRobot -root head -root lower -root chest -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("dupRobot")) self.failUnless(MayaCmds.objExists("head")) self.failUnless(MayaCmds.objExists("lower")) self.failUnless(MayaCmds.objExists("chest")) self.failIf(MayaCmds.objExists("robot")) self.failIf(MayaCmds.objExists("robot|body"))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util def getObjFromName(nodeName): selectionList = OpenMaya.MSelectionList() selectionList.add(nodeName) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj class PolyNormalsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSet_noNormals_Attr(self): MayaCmds.polyCube(name='polyCube') # add the necessary props MayaCmds.select('polyCubeShape') MayaCmds.addAttr(longName='subDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='interpolateBoundary', attributeType='bool', defaultValue=True) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='faceVaryingInterpolateBoundary', attributeType='bool', defaultValue=False) MayaCmds.polySphere(name='polySphere') # add the necessary props MayaCmds.select('polySphereShape') MayaCmds.addAttr(longName='subDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='interpolateBoundary', attributeType='bool', defaultValue=True) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=True) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='faceVaryingInterpolateBoundary', attributeType='bool', defaultValue=False) #ignore facevaryingType, subdPaintLev MayaCmds.group('polyCube', 'polySphere', name='polygons') self.__files.append(util.expandFileName('staticPoly_noNormals_AttrTest.abc')) MayaCmds.AbcExport(j='-root polygons -f ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open', debug=False) # make sure the noNormal attribute is set correctly when the file is loaded self.failIf(MayaCmds.listAttr('polyCubeShape').count('noNormals') != 0) self.failUnless(MayaCmds.getAttr('polySphereShape.noNormals')) def testStaticMeshPolyNormals(self): # create a polygon cube polyName = 'polyCube' polyShapeName = 'polyCubeShape' MayaCmds.polyCube( sx=1, sy=1, sz=1, name=polyName, constructionHistory=False) # add the necessary props MayaCmds.select(polyShapeName) MayaCmds.addAttr(longName='subDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) # tweek some normals MayaCmds.select(polyName+'.vtxFace[2][1]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(0.707107, 0.707107, 0)) MayaCmds.select(polyName+'.vtxFace[7][4]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(-0.707107, 0.707107, 0)) # write to file self.__files.append(util.expandFileName('staticPolyNormalsTest.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (polyName, self.__files[-1])) # read back from file MayaCmds.AbcImport(self.__files[-1], mode='import') self.failIf(MayaCmds.listAttr('polyCube1|polyCubeShape').count('noNormals') != 0) # make sure the normals are the same shapeObj = getObjFromName('polyCube1|polyCubeShape') fnMesh = OpenMaya.MFnMesh(shapeObj) numFaces = fnMesh.numPolygons() for faceIndex in range(0, numFaces): vertexList = OpenMaya.MIntArray() fnMesh.getPolygonVertices(faceIndex, vertexList) numVertices = vertexList.length() for v in range(0, numVertices): vertexIndex = vertexList[v] normal = OpenMaya.MVector() fnMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal) vtxFaceAttrName = '.vtxFace[%d][%d]' % (vertexIndex, faceIndex) MayaCmds.select(polyName+vtxFaceAttrName, replace=True) oNormal = MayaCmds.polyNormalPerVertex( query=True, xyz=True) self.failUnlessAlmostEqual(normal[0], oNormal[0], 4) self.failUnlessAlmostEqual(normal[1], oNormal[1], 4) self.failUnlessAlmostEqual(normal[2], oNormal[2], 4) def testAnimatedMeshPolyNormals(self): # create a polygon cube polyName = 'polyCube' polyShapeName = 'polyCubeShape' MayaCmds.polyCube(sx=1, sy=1, sz=1, name=polyName, constructionHistory=False) # add the necessary props MayaCmds.select(polyShapeName) MayaCmds.addAttr(longName='subDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) # tweek some normals MayaCmds.select(polyName+'.vtxFace[2][1]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(0.707107, 0.707107, 0)) MayaCmds.select(polyName+'.vtxFace[7][4]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(-0.707107, 0.707107, 0)) # set keyframes to make sure normals are written out as animated MayaCmds.setKeyframe(polyShapeName+'.vtx[0:7]', time=[1, 4]) MayaCmds.currentTime(2, update=True) MayaCmds.select(polyShapeName+'.vtx[0:3]') MayaCmds.move(0, 0.5, 1, relative=True) MayaCmds.setKeyframe(polyShapeName+'.vtx[0:7]', time=[2]) # write to file self.__files.append(util.expandFileName('animPolyNormalsTest.abc')) MayaCmds.AbcExport(j='-fr 1 4 -root %s -f %s' % (polyName, self.__files[-1])) # read back from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the noNormal attribute is set correctly when the file is # loaded self.failIf(MayaCmds.listAttr('polyCube1|polyCubeShape').count('noNormals') != 0) # make sure the normals are the same for time in range(1, 5): MayaCmds.currentTime(time, update=True) shapeObj = getObjFromName('polyCube1|polyCubeShape') fnMesh = OpenMaya.MFnMesh(shapeObj) numFaces = fnMesh.numPolygons() for faceIndex in range(0, numFaces): vertexList = OpenMaya.MIntArray() fnMesh.getPolygonVertices(faceIndex, vertexList) numVertices = vertexList.length() for v in range(0, numVertices): vertexIndex = vertexList[v] normal = OpenMaya.MVector() fnMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal) vtxFaceAttrName = '.vtxFace[%d][%d]' % (vertexIndex, faceIndex) MayaCmds.select(polyName+vtxFaceAttrName, replace=True) oNormal = MayaCmds.polyNormalPerVertex(query=True, xyz=True) self.failUnlessAlmostEqual(normal[0], oNormal[0], 4) self.failUnlessAlmostEqual(normal[1], oNormal[1], 4) self.failUnlessAlmostEqual(normal[2], oNormal[2], 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createCamera(): name = MayaCmds.camera() MayaCmds.setAttr(name[1]+'.horizontalFilmAperture', 0.962) MayaCmds.setAttr(name[1]+'.verticalFilmAperture', 0.731) MayaCmds.setAttr(name[1]+'.focalLength', 50) MayaCmds.setAttr(name[1]+'.focusDistance', 5) MayaCmds.setAttr(name[1]+'.shutterAngle', 144) return name class cameraTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticCameraReadWrite(self): name = createCamera() # write to file self.__files.append(util.expandFileName('testStaticCameraReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name[0], self.__files[-1])) # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') camList = MayaCmds.ls(type='camera') self.failUnless(util.compareCamera(camList[0], camList[1])) def testAnimCameraReadWrite(self): name = createCamera() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture') MayaCmds.setKeyframe(name[1], attribute='focalLength') MayaCmds.setKeyframe(name[1], attribute='focusDistance') MayaCmds.setKeyframe(name[1], attribute='shutterAngle') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe(name[1], attribute='focalLength', value=40) MayaCmds.setKeyframe(name[1], attribute='focusDistance', value=5.4) MayaCmds.setKeyframe(name[1], attribute='shutterAngle', value=174.94) self.__files.append(util.expandFileName('testAnimCameraReadWrite.abc')) self.__files.append(util.expandFileName('testAnimCameraReadWrite01_14.abc')) self.__files.append(util.expandFileName('testAnimCameraReadWrite15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') camList = MayaCmds.ls(type='camera') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareCamera(camList[0], camList[1]): self.fail('%s and %s are not the same at frame %d' % (camList[0], camList[1], t))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import maya.cmds as MayaCmds import os import subprocess import unittest import util class AnimTransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimTransformReadWrite(self): nodeName = MayaCmds.createNode('transform', n='test') # shear MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXY', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearYZ', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXZ', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=1.5, attribute='shearXY', t=12) MayaCmds.setKeyframe(nodeName, value=5, attribute='shearYZ', t=12) MayaCmds.setKeyframe(nodeName, value=2.5, attribute='shearXZ', t=12) # translate MayaCmds.setKeyframe('test', value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='translateY', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='translateZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.5, attribute='translateX', t=12) MayaCmds.setKeyframe('test', value=5, attribute='translateY', t=12) MayaCmds.setKeyframe('test', value=2.5, attribute='translateZ', t=12) # rotate MayaCmds.setKeyframe('test', value=0, attribute='rotateX', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='rotateY', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='rotateZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=24, attribute='rotateX', t=12) MayaCmds.setKeyframe('test', value=53, attribute='rotateY', t=12) MayaCmds.setKeyframe('test', value=90, attribute='rotateZ', t=12) # scale MayaCmds.setKeyframe('test', value=1, attribute='scaleX', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='scaleY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='scaleZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.2, attribute='scaleX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleY', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleZ', t=12) # rotate pivot MayaCmds.setKeyframe('test', value=0.5, attribute='rotatePivotX', t=[1, 24]) MayaCmds.setKeyframe('test', value=-0.1, attribute='rotatePivotY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='rotatePivotZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=0.8, attribute='rotatePivotX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='rotatePivotY', t=12) MayaCmds.setKeyframe('test', value=-1, attribute='rotatePivotZ', t=12) # scale pivot MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotX', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.0, attribute='scalePivotY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.4, attribute='scalePivotX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotY', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotZ', t=12) self.__files.append(util.expandFileName('testAnimTransformReadWrite.abc')) self.__files.append(util.expandFileName('testAnimTransformReadWrite01_14.abc')) self.__files.append(util.expandFileName('testAnimTransformReadWrite15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root test -file ' + self.__files[-2]) MayaCmds.AbcExport(j='-fr 15 24 -root test -file ' + self.__files[-1]) subprocess.call(self.__abcStitcher + self.__files[-3:]) MayaCmds.AbcImport(self.__files[-3], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotZ')) # frame 12 MayaCmds.currentTime(12, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(5, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(2.5, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(5, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(2.5, MayaCmds.getAttr('test.translateZ')) self.failUnlessAlmostEqual(24.0, MayaCmds.getAttr('test.rotateX'), 4) self.failUnlessAlmostEqual(53.0, MayaCmds.getAttr('test.rotateY'), 4) self.failUnlessAlmostEqual(90.0, MayaCmds.getAttr('test.rotateZ'), 4) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.8, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(-1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.4, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scalePivotZ')) # frame 24 MayaCmds.currentTime(24, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotZ')) def testSampledConnectionDetectionRW(self): # connect to plugs at parent level and see if when loaded back # the sampled channels are recognized correctly driver = MayaCmds.createNode('transform', n='driverTrans') # shear MayaCmds.setKeyframe(driver, value=0, attribute='shearXY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='shearYZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='shearXZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.5, attribute='shearXY', t=12) MayaCmds.setKeyframe(driver, value=5, attribute='shearYZ', t=12) MayaCmds.setKeyframe(driver, value=2.5, attribute='shearXZ', t=12) # translate MayaCmds.setKeyframe(driver, value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='translateY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='translateZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.5, attribute='translateX', t=12) MayaCmds.setKeyframe(driver, value=5, attribute='translateY', t=12) MayaCmds.setKeyframe(driver, value=2.5, attribute='translateZ', t=12) # rotate MayaCmds.setKeyframe(driver, value=0, attribute='rotateX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='rotateY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='rotateZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=24, attribute='rotateX', t=12) MayaCmds.setKeyframe(driver, value=53, attribute='rotateY', t=12) MayaCmds.setKeyframe(driver, value=90, attribute='rotateZ', t=12) # scale MayaCmds.setKeyframe(driver, value=1, attribute='scaleX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='scaleY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='scaleZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.2, attribute='scaleX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scaleY', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scaleZ', t=12) # rotate pivot MayaCmds.setKeyframe(driver, value=0.5, attribute='rotatePivotX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=-0.1, attribute='rotatePivotY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='rotatePivotZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0.8, attribute='rotatePivotX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='rotatePivotY', t=12) MayaCmds.setKeyframe(driver, value=-1, attribute='rotatePivotZ', t=12) # scale pivot MayaCmds.setKeyframe(driver, value=1.2, attribute='scalePivotX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.0, attribute='scalePivotY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.2, attribute='scalePivotZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.4, attribute='scalePivotX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scalePivotY', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scalePivotZ', t=12) # create the transform node that's been driven by the connections driven = MayaCmds.createNode('transform', n = 'drivenTrans') MayaCmds.connectAttr(driver+'.translate', driven+'.translate') MayaCmds.connectAttr(driver+'.scale', driven+'.scale') MayaCmds.connectAttr(driver+'.rotate', driven+'.rotate') MayaCmds.connectAttr(driver+'.shear', driven+'.shear') MayaCmds.connectAttr(driver+'.rotatePivot', driven+'.rotatePivot') MayaCmds.connectAttr(driver+'.scalePivot', driven+'.scalePivot') self.__files.append(util.expandFileName('testSampledTransformDetection.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root drivenTrans -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotZ')) # frame 12 MayaCmds.currentTime(12, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(5, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(2.5, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(5, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(2.5, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessAlmostEqual(24.0, MayaCmds.getAttr(driven+'.rotateX'), 4) self.failUnlessAlmostEqual(53.0, MayaCmds.getAttr(driven+'.rotateY'), 4) self.failUnlessAlmostEqual(90.0, MayaCmds.getAttr(driven+'.rotateZ'), 4) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.8, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(-1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.4, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scalePivotZ')) # frame 24 MayaCmds.currentTime(24, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotZ'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic, nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** #!/usr/bin/env python sprops = \ """ IBoolProperty IUcharProperty ICharProperty IUInt16Property IInt16Property IUInt32Property IInt32Property IUInt64Property IInt64Property IHalfProperty IFloatProperty IDoubleProperty IStringProperty IWstringProperty IV2sProperty IV2iProperty IV2fProperty IV2dProperty IV3sProperty IV3iProperty IV3fProperty IV3dProperty IBox2sProperty IBox2iProperty IBox2fProperty IBox2dProperty IBox3sProperty IBox3iProperty IBox3fProperty IBox3dProperty IM33fProperty IM33dProperty IM44fProperty IM44dProperty IQuatfProperty IQuatdProperty IC3hProperty IC3fProperty IC3cProperty IC4hProperty IC4fProperty IC4cProperty IN3fProperty IN3dProperty """ def printdefs( p ): s = " //%s\n //\n" #s += 'bool\n( Abc::%s::*matchesMetaData )( const AbcA::MetaData&,\nAbc::SchemaInterpMatching ) = \\\n' #s += '&Abc::%s::matches;\n\n' #s += 'bool\n( Abc::%s::*matchesHeader )( const AbcA::PropertyHeader&,\nAbc::SchemaInterpMatching ) = \\\n' #s += '&Abc::%s::matches;\n\n' s += 'class_<Abc::%s>( "%s",\ninit<Abc::ICompoundProperty,\nconst std::string&>() )\n' s += '.def( init<>() )\n' s += '.def( "getName", &Abc::%s::getName,\nreturn_value_policy<copy_const_reference>() )\n' s += '.def( "getHeader", &Abc::%s::getHeader,\nreturn_internal_reference<1>() )\n' s += '.def( "isScalar", &Abc::%s::isScalar )\n' s += '.def( "isArray", &Abc::%s::isArray )\n' s += '.def( "isCompound", &Abc::%s::isCompound )\n' s += '.def( "isSimple", &Abc::%s::isSimple )\n' s += '.def( "getMetaData", &Abc::%s::getMetaData,\nreturn_internal_reference<1>() )\n' s += '.def( "getDataType", &Abc::%s::getDataType,\nreturn_internal_reference<1>() )\n' s += '.def( "getTimeSamplingType", &Abc::%s::getTimeSamplingType )\n' s += '.def( "getInterpretation", &Abc::%s::getInterpretation,\nreturn_value_policy<copy_const_reference>() )\n' #s += '.def( "matches", matchesMetaData )\n' #s += '.def( "matches", matchesHeader )\n' s += '.def( "getNumSamples", &Abc::%s::getNumSamples )\n' #s += '.def( "getValue", &Abc::%s::getValue, %s_overloads() )\n' s += '.def( "getObject", &Abc::%s::getObject,\nwith_custodian_and_ward_postcall<0,1>() )\n' s += '.def( "reset", &Abc::%s::reset )\n' s += '.def( "valid", &Abc::%s::valid )\n' s += '.def( "__str__", &Abc::%s::getName,\nreturn_value_policy<copy_const_reference>() )\n' s += '.def( "__nonzero__", &Abc::%s::valid )\n' s += ';' print s % eval( "%s" % ( 'p,' * s.count( r'%s' ) ) ) print return for i in sprops.split(): if i == "": pass else: printdefs( i )
Python
#!/usr/bin/env python2.5 #-*- mode: python -*- ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Industrial Light & Magic nor the names of ## its contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import os, sys class Path( object ): """The Path class simplifies filesystem path manipulation. If you wish to use a Path object as an argument to standard Python path functions such as os.path.*, open(), etc., you must first cast it to a string like "str( myPathObject )".""" def __init__( self, path=None ): if path != None: path = str( path ) self._isabs = os.path.isabs( path ) self._orig = path self._path = os.path.normpath( os.path.expanduser( path ) ) else: self._isabs = False self._path = '' self._orig = '' if self._isabs: self._root = os.sep else: if self._orig == '': self._root = None else: self._root = os.curdir self._plist = filter( lambda x: x and x != os.curdir, self._path.split( os.sep )) self._len = len( self._plist ) self._isempty = self._root == None and self._len == 0 self._maxindex = self._len - 1 self._maxsliceindex = self._len def __reinit__( self, new ): self._len = len( new._plist ) self._plist = new._plist[:] self._isempty = 0 == new._len self._maxindex = new._len - 1 self._maxsliceindex = new._len self._path = new._path self._orig = new._orig self._isabs = new._isabs self._root = new._root def __repr__( self ): return self._path def __str__( self ): return self.__repr__() def __contains__( self, other ): return other in self._plist def __len__( self ): return self._len def __add__( self, other ): return Path( os.path.join( str( self ), str( other ) ) ) def __radd__( self, other ): return Path( other ) + self def __iter__( self ): self._iterindex = 0 return self def __eq__( self, other ): return str( self ) == str( other ) def __ne__( self, other ): return str( self ) != str( other ) def __cmp__( self, other ): _, p1, p2 = self.common( other ) return len( p1 ) - len( p2 ) def __nonzero__( self ): if not self.isabs() and len( self ) == 0: return False else: return True def __hash__( self ): return hash( str( self )) def __getitem__( self, n ): if isinstance( n, slice ): path = None plist = self._plist[n.start:n.stop:n.step] returnabs = self._isabs and n.start < 1 if len( plist ) > 0: path = os.sep.join( plist ) else: path = os.curdir path = Path( path ) if returnabs: path = self.root() + path else: pass return path else: return self._plist[n] def __setitem__( self, key, value ): try: key = int( key ) except ValueError: raise ValueError, "You must use an integer to refer to a path element." if key > abs( self._maxindex ): raise IndexError, "Maximum index is +/- %s." % self._maxindex self._plist[key] = value self._path = str( self[:] ) def __delitem__( self, n ): try: n = int( n ) except ValueError: raise ValueError, "You must use an integer to refer to a path element." try: del( self._plist[n] ) t = Path( self[:] ) self.__reinit__( t ) except IndexError: raise IndexError, "Maximum index is +/- %s" & self._maxindex def rindex( self, val ): if val in self: return len( self._plist ) - \ list( reversed( self._plist ) ).index( val ) - 1 else: raise ValueError, "%s is not in path." % val def index( self, val ): if val in self: return self._plist.index( val ) else: raise ValueError, "%s is not in path." % val def common( self, other, cmn=None ): cmn = Path( cmn ) other = Path( str( other ) ) if self.isempty() or other.isempty(): return cmn, self, other elif (self[0] != other[0]) or (self.root() != other.root()): return cmn, self, other else: return self[1:].common( other[1:], self.root() + cmn + self[0] ) def relative( self, other ): cmn, p1, p2 = self.common( other ) relhead = Path() if len( p1 ) > 0: relhead = Path( (os.pardir + os.sep) * len( p1 )) return relhead + p2 def join( self, *others ): t = self[:] for o in others: t = t + o return t def split( self ): head = self[:-1] tail = None if not head.isempty(): tail = Path( self[-1] ) else: tail = self if not head.isabs() and head.isempty(): head = Path( None ) if head.isabs() and len( tail ) == 1: tail = tail[-1] return ( head, tail ) def splitext( self ): head, tail = os.path.splitext( self._path ) return Path( head ), tail def next( self ): if self._iterindex > self._maxindex: raise StopIteration else: i = self._iterindex self._iterindex += 1 return self[i] def subpaths( self ): sliceind = 0 while sliceind < self._maxsliceindex: sliceind += 1 yield self[:sliceind] def append( self, *others ): t = self[:] for o in others: t = t + o self.__reinit__( t ) def root( self ): return Path( self._root ) def elems( self ): return self._plist def path( self ): return self._path def exists( self ): return os.path.exists( self._path ) def isempty( self ): return self._isempty def isabs( self ): return self._isabs def islink( self ): return os.path.islink( self._path ) def isdir( self ): return os.path.isdir( self._path ) def isfile( self ): return os.path.isfile( self._path ) def readlink( self ): if self.islink(): return Path( os.readlink( self._orig ) ) else: return self def dirname( self ): return self[:-1] def basename( self ): return self.dirname() def startswith( self, other ): return self._path.startswith( other ) def makeabs( self ): t = self[:] t._root = os.sep t._isabs = True t._path = os.path.join( os.sep, self._path ) self.__reinit__( t ) def makerel( self ): t = self[:] t._root = os.curdir t._isabs = False t._path = os.sep.join( t._plist ) self.__reinit__( t ) def toabs( self ): return Path( os.path.abspath( self._path ) ) def torel( self ): t = self[:] t.makerel() return t ##-***************************************************************************** def mapFSTree( root, path, dirs=set(), links={} ): """Create a sparse map of the filesystem graph from the root node to the path node.""" root = Path( root ) path = Path( path ) for sp in path.subpaths(): if sp.isabs(): full = sp else: full = sp.toabs() head = full.dirname() if full.islink(): target = full.readlink() if target.isabs(): newpath = target else: newpath = head + target # make sure there are no cycles if full in links: continue links[full] = newpath _dirs, _links = mapFSTree( full, newpath, dirs, links ) dirs.update( _dirs ) links.update( _links ) elif full.isdir(): if full in dirs: continue else: dirs.add( full ) elif full.isfile(): break #pass else: print "QOI??? %s" % full return dirs, links ##-***************************************************************************** def main(): try: arg = Path( sys.argv[1] ) except IndexError: print "Please supply a directory to analyze." return 1 dirs, links = mapFSTree( Path( os.getcwd() ), arg ) print print "Directories traversed to get to %s\n" % arg for d in sorted( list( dirs ) ): print d print print "Symlinks in traversed directories for %s\n" % arg for k in links: print "%s: %s" % ( k, links[k] ) print return 0 ##-***************************************************************************** if __name__ == "__main__": sys.exit( main() )
Python
#!/usr/bin/env python2.6 #-*- mode: python -*- ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Industrial Light & Magic nor the names of ## its contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from __future__ import with_statement import os, sys, re from Path import Path ##-***************************************************************************** COMMENT = re.compile( r"//|#" ) WS = re.compile( r"\s" ) ##-***************************************************************************** class CacheEntry( object ): def __init__( self, _line ): line = WS.sub( "", str( _line ) ) if not line: return None elif COMMENT.match( line ): return None else: # get rid of comments at the end of the line line = COMMENT.split( line, 1 )[0].strip() try: name_type, value = line.split( '=' ) self._value = value.strip() if self._value == '': self._value = None name, typ = name_type.split( ':' ) self._name = name.strip() self._type = typ.strip() except ValueError: sys.stderr.write( "Could not parse line '%s'\n" % _line ) self._value = None self._name = None self._type = None def __str__( self ): val = "" typ = "" if self._value != None: val = self._value if self._type != None: typ = self._type if self._name == None: return "" else: s = "%s:%s=%s" % ( self._name, typ, val ) return s.strip() def __eq__( self, other ): return str( self ) == str( other ) def __nonzero__( self ): try: return self._name != None and self._value != None except AttributeError: return False def name( self ): return self._name def value( self, newval = None ): if newval != None: self._value = newval else: return self._value def hint( self ): """Return the CMakeCache TYPE of the entry; used as a hint to CMake GUIs.""" return self._type ##-***************************************************************************** class CMakeCache( object ): """This class is used to read in and get programmatic access to the variables in a CMakeCache.txt file, manipulate them, and then write the cache back out.""" def __init__( self, path=None ): self._cachefile = Path( path ) _cachefile = str( self._cachefile ) self._entries = {} if self._cachefile.exists(): with open( _cachefile ) as c: entries = filter( None, map( lambda x: CacheEntry( x ), c.readlines() ) ) entries = filter( lambda x: x.value() != None, entries ) for i in entries: self._entries[i.name()] = i def __contains__( self, thingy ): try: return thingy in self.names() except TypeError: return thingy in self._entries.values() def __iter__( self ): return self._entries def __nonzero__( self ): return len( self._entries ) > 0 def __str__( self ): return os.linesep.join( map( lambda x: str( x ), self.entries() ) ) def add( self, entry ): e = CacheEntry( entry ) if e: if not e in self: self._entries[e.name()] = e else: sys.stderr.write( "Entry for '%s' is already in the cache.\n" % \ e.name() ) else: sys.stderr.write( "Could not create cache entry for '%s'\n" % e ) def update( self, entry ): e = CacheEntry( entry ) if e: self._entries[e.name()] = e else: sys.stderr.write( "Could not create cache entry for '%s'\n" % e ) def names( self ): return self._entries.keys() def entries( self ): return self._entries.values() def get( self, name ): return self._entries[name] def cachefile( self ): return self._cachefile def refresh( self ): self.__init__( self._cachefile ) def write( self, newfile = None ): if newfile == None: newfile = self._cachefile with open( newfile, 'w' ) as f: for e in self.entries(): f.write( str( e ) + os.linesep )
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic, nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from Path import Path from CMakeCache import CMakeCache, CacheEntry
Python
#!/usr/bin/env python import time t = time.time() u = time.gmtime(t) s = time.strftime('%a, %e %b %Y %T GMT', u) print 'Content-Type: text/javascript' print 'Cache-Control: no-cache' print 'Date: ' + s print 'Expires: ' + s print '' print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
Python
#!/usr/bin/env python import codecs import re import jinja2 import markdown def process_slides(): with codecs.open('../../presentation-output.html', 'w', encoding='utf8') as outfile: md = codecs.open('slides.md', encoding='utf8').read() md_slides = md.split('\n---\n') print 'Compiled %s slides.' % len(md_slides) slides = [] # Process each slide separately. for md_slide in md_slides: slide = {} sections = md_slide.split('\n\n') # Extract metadata at the beginning of the slide (look for key: value) # pairs. metadata_section = sections[0] metadata = parse_metadata(metadata_section) slide.update(metadata) remainder_index = metadata and 1 or 0 # Get the content from the rest of the slide. content_section = '\n\n'.join(sections[remainder_index:]) html = markdown.markdown(content_section) slide['content'] = postprocess_html(html, metadata) slides.append(slide) template = jinja2.Template(open('base.html').read()) outfile.write(template.render(locals())) def parse_metadata(section): """Given the first part of a slide, returns metadata associated with it.""" metadata = {} metadata_lines = section.split('\n') for line in metadata_lines: colon_index = line.find(':') if colon_index != -1: key = line[:colon_index].strip() val = line[colon_index + 1:].strip() metadata[key] = val return metadata def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" if metadata.get('build_lists') and metadata['build_lists'] == 'true': html = html.replace('<ul>', '<ul class="build">') html = html.replace('<ol>', '<ol class="build">') return html if __name__ == '__main__': process_slides()
Python
# -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUnicode.py'), 'z:/home/pankaj/programming/python/billiards/src/billiards/billiards.py'], pathex=['Z:\\mnt\\data\\Program Installers\\Programs\\Programming\\py\\py26win']) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build\\pyi.win32\\billiards_pyinstaller', 'billiards.exe'), debug=False, strip=False, upx=True, console=False ) data = Tree(root='z:\\home\\pankaj\\programming\\python\\billiards\\src\\billiards\\data', prefix='data', excludes=None) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, data, strip=False, upx=True, name=os.path.join('dist', 'billiards'))
Python
#!/usr/bin/env python from distutils.core import setup setup(name='PyBilliards', version=open('VERSION').read().strip(), description='A simple 2D billiards game', long_description='''A simple 2D billiards game written in python using pygame''', classifiers=['Topic :: Games/Entertainment', 'Topic :: Software Development :: Libraries :: pygame'], author='Prashant Agrawal & Pankaj Pandey', author_email='agrawal.prash@gmail.com,pankaj86@gmail.com', url='http://code.google.com/p/pybilliards/', package_dir = {'': 'src'}, packages=['billiards'], package_data={'billiards': ['data/themes/*/*']}, license = 'GPLv3+', )
Python
# -*- coding: utf-8 -*- import logging import os import settings_default # TODO: replace platform specific paths class Settings(object): def __init__(self): self._settings = {} #self.add_from_file(os.path.join('settings_default.py')) self._settings.update(settings_default.settings) self.userdir = self._settings['userdir'] self.add_from_file(os.path.join(self.userdir,'user_settings.py')) logging.basicConfig(level=getattr(logging,self._settings['loglevel'].upper())) def get(self, key): keys = key.split('.') value = self._settings try: for k in keys: value = value[k] except KeyError: logging.info('No setting found for key: %s'%key) value = None return value def set(self, key, value): keys = key.split('.') v = self._settings for k in keys[:-1]: try: v = v[k] except KeyError: v[k] = {} v = v[k] v[keys[-1]] = value def add_from_file(self, filename): d = {} try: execfile(filename, d) data = d['settings'] self._settings.update(data) except Exception, exc: # any log call before basicConfig results in failure to set the log level #logging.warn(repr(exc)) #logging.warn('Unable to load settings from: %s'%filename) pass settings = Settings()
Python
#! /usr/bin/env python # -*- coding: utf-8 -*- '''A simple 2D billiards game @authors: prashant agrawal, pankaj pandey (c) 2010 the authors ''' # changelog # pankaj : 17 March, 2010: fixed alignment of the cue with the ball # and made the target of the cue as the ball center instead of the mouse pos # authors : before 17 March, 2010: did most of the setup import pygame, sys, os, random from pygame.locals import * import time, pdb from math import * from ball import * from numpy import * from settings import settings from theme import get_theme import logging if not pygame.font: print "Warning, fonts disabled!" if not pygame.mixer: print "Warning, sounds disabled!" RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) YELLOW = (255, 255, 0) mod = lambda v: sqrt(v[0] * v[0] + v[1] * v[1]) class Player: def __init__(self,board,ID,name=None): ''' ID: ID denotes a number the user wants to assign to current player as identification mark ''' self.board = board self.score = 0 self.ID = ID self.name = name if name is not None else 'Player '+str(ID+1) self.is_active = False class Scoreboard(pygame.sprite.Sprite): def __init__(self,board): pygame.sprite.Sprite.__init__(self) self.board = board self.players = self.board.players self.set_active_player(self.players[0]) self.set_new_active_player() def set_active_player(self,player): for p in self.players: if p is player: p.is_active = True self.active_player = player else: p.is_active = False self.new_active_player = self.active_player self.display() def set_new_active_player(self): activeplayer_index = self.players.index(self.active_player) if activeplayer_index==len(self.players)-1: activeplayer_index = -1 self.new_active_player = self.players[activeplayer_index + 1] def set_scores(self,scores): ''' Sets all the scores according to a list of scores provided by 'scores'. ''' for i,player in enumerate(self.players): player.score = scores[i] def update(self,ball): ''' Updates score of current player by +1 if any non-white ball goes to holes and -1 if white ball goes to hole. ''' if ball is self.board.whiteball: self.active_player.score -= 1 else: self.active_player.score += 1 self.display() def display(self): print '' print 'Player ID\tScore\tStatus' underline = lambda s: '='*len(s) print underline('Player ID')+'\t'+underline('Score')+'\t'+underline('Status') for player in self.board.players: status = '* Active' if player.is_active else 'Idle' print '%s\t%s\t'%(player.name,player.score) + status class Cue(pygame.sprite.Sprite): def __init__(self, board): pygame.sprite.Sprite.__init__(self) self.board = board self.image = self.board.theme.get_cue() self.rect = self.image.get_rect() self.CUE_WIDTH = self.rect.width self.CUE_LENGTH = self.rect.height self.originalcopy = pygame.transform.scale(self.image, (self.CUE_WIDTH, self.CUE_LENGTH)) #self.image = pygame.transform.scale(self.image, (self.CUE_WIDTH, self.CUE_LENGTH)) #self.rect = self.image.get_rect() #self.rect.width = 1 #self.rect.left = self.CUE_WIDTH/2.0 self.speed = zeros((2,)) self.radius = self.rect.centery - self.rect.top def update(self, dest, mousepressed): src = self.board.whiteball.pos if mousepressed: dest_minus_src = (dest[0]-src[0],dest[1]-src[1]) angle = atan2(dest_minus_src[0],dest_minus_src[1]) c, s = cos(angle), sin(angle) angle = 180.0/pi*angle t = self.CUE_WIDTH/2.0 l = self.CUE_LENGTH/2.0 h = l*c+t*s w = s*(h+s*t)/c self.image = pygame.transform.rotate(self.originalcopy, angle) irect = self.image.get_rect() left,top = dest self.rect.width = irect.width self.rect.height = irect.height if 0<=angle<=90: top -= t*s left -= t*c elif 90<=angle<=180: top -= irect.height top += t*s left += t*c elif -90<=angle<0: left -= irect.width top += t*s left += t*c else: top -= irect.height left -= irect.width top -= t*s left -= t*c self.rect.topleft = left,top else: MAX_DRAG = self.board.height / 8.0 if dest is not None: self.speed = array([-(dest[0]-src[0])*self.board.VEL_MAX/MAX_DRAG,-(dest[1]-src[1])*self.board.VEL_MAX/MAX_DRAG]) if hypot(*self.speed)<1: return # defining the convention that in initballpos and initballspeed, whiteball is always at the end self.board.initballspeed = [b.speed for b in self.board.ballsprites.sprites() if b is not self.board.whiteball] + [self.board.whiteball.speed] self.board.initballpos = [b.pos for b in self.board.ballsprites.sprites() if b is not self.board.whiteball] + [self.board.whiteball.pos] self.board.initcuespeed = self.speed.copy() self.board.inittopleft = self.rect.topleft self.board.initrect = self.rect while not self.board.collide_cue(self): #while not self.hitting_ball.rect.collidepoint(self.rect.center): time.sleep(0.01) self.board.cuesprite.clear(self.board.screen, self.board.background) self.rect.move_ip(round(self.speed[0]), round(self.speed[1])) self.board.draw() class Billiards(): def __init__(self, width=600, height=375, n_balls=7, nplayers=2, caption='Billiards', friction=True, theme=None,): pygame.init() self.theme = get_theme(theme) self.ballsprites = pygame.sprite.RenderPlain() self.holesprites = pygame.sprite.RenderPlain() self.cuesprite = pygame.sprite.RenderPlain() self.players = [Player(self,i) for i in range(nplayers)] self.scoreboard = Scoreboard(self) self.new_player_set = False self.width, self.height, self.n_balls = width, height, n_balls self.RUNNING, self.VEL_MAX = False, 5 if friction == True: self.friction = 2.5 * self.VEL_MAX ** 2 / float(4 * self.height) else: self.friction = 0.0 self.screen = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption(caption) self.background = self.theme.get_background() self.screen.blit(self.background, (0,0)) self.whiteball = None self.generate_balls() self.init_consts() self.draw() self.replaying = False self.wait = 0.01 # time in seconds to wait after each timestep pygame.mixer.init() self.collidecue_sound = self.theme.get_collide_snd() self.gotoholes_sound = self.theme.get_gotoholes_snd() self.finishmessage = self.theme.get_finish_snd() def generate_balls(self, posarr=None, speeds=None): n = 0 nballs = len(posarr) - 1 if posarr is not None else self.n_balls while n < nballs: newball = Ball((0, 0), self) self.radius = newball.radius vel = array((0, 0)) if speeds is None else speeds[n] pos = array(((random.uniform(self.radius, self.width - self.radius)), (random.uniform(self.radius, self.height - self.radius)))) if posarr is None else posarr[n] newball.set_pos(pos) newball.speed = vel if n == 0: self.ballsprites.add(newball) n = n + 1 else: collide = False for oldball in self.ballsprites.sprites() + self.holesprites.sprites(): if newball.rect.colliderect(oldball.rect): collide = True if not collide: self.ballsprites.add(newball) n += 1 if posarr is not None: whiteballpos = posarr[-1] whiteballspeed = speeds[-1] self.whiteball = Ball(whiteballpos, self, vel=whiteballspeed, is_white=True) # making last ball on posarr and speeds as new whiteball else: self.whiteball = Ball(array([self.width / 2.0, self.height / 2.0]), self, is_white=True) self.ballsprites.add(self.whiteball) def init_consts(self): rad = self.radius self.LEFTTOP = (rad, rad) self.MIDDLETOP = (int(self.width / 2.0), rad) self.RIGHTTOP = (self.width - rad, rad) self.LEFTBOTTOM = (rad, self.height - rad) self.MIDDLEBOTTOM = (int(self.width / 2.0), self.height - rad) self.RIGHTBOTTOM = (self.width - rad, self.height - rad) def draw_holes(self): self.hole_radius = rad = int(1.2 * self.radius) lefttoprect = pygame.draw.circle(self.screen, BLACK, self.LEFTTOP, rad) middletoprect = pygame.draw.circle(self.screen, BLACK, self.MIDDLETOP, rad) righttoprect = pygame.draw.circle(self.screen, BLACK, self.RIGHTTOP, rad) leftbottomrect = pygame.draw.circle(self.screen, BLACK, self.LEFTBOTTOM, rad) middlebottomrect = pygame.draw.circle(self.screen, BLACK, self.MIDDLEBOTTOM, rad) rightbottomrect = pygame.draw.circle(self.screen, BLACK, self.RIGHTBOTTOM, rad) self.holerectlist = [lefttoprect, middletoprect, righttoprect, leftbottomrect, middlebottomrect, rightbottomrect] def draw(self): self.draw_holes() self.ballsprites.draw(self.screen) if not len(self.cuesprite.sprites()) == 0: self.cuesprite.draw(self.screen) pygame.display.flip() def after_one_timestep(self): self.screen.blit(self.background, (0, 0)) self.ballsprites.update() self.draw() #energy = sum([dot(i.speed,i.speed) for i in self.ballsprites.sprites()]) #print 'Total Energy', energy for ball in self.ballsprites.sprites(): if mod(ball.speed) > self.friction: self.runningballs = True return def collide_ball(self, ball1, ball2): if ball1.rect.colliderect(ball2.rect): r = self.radius r21 = array([ball1.rect.center[0] - ball2.rect.center[0], ball1.rect.center[1] - ball2.rect.center[1]]) dist = hypot(*r21) if dist < 2 * r: dirx_unit, diry_unit = dir_unit = r21 / dist next_int = lambda x: ceil(x) if x > 0 else floor(x) vr1 = dot(ball1.speed, dir_unit) vr2 = dot(ball2.speed, dir_unit) dvr = vr2 - vr1 ball2.speed[:] = ball2.speed - dvr * dir_unit ball1.speed[:] = ball1.speed + dvr * dir_unit ball2.set_pos(ball2.pos+array((next_int(0.5 * r21[0] - r * dirx_unit), next_int(0.5 * r21[1] - r * diry_unit)))) ball1.set_pos(ball1.pos+array((next_int(-0.5 * r21[0] + r * dirx_unit), next_int(-0.5 * r21[1] + r * diry_unit)))) newdist = hypot(ball1.rect.center[0] - ball2.rect.center[0], ball1.rect.center[1] - ball2.rect.center[1]) vr1 = dot(ball1.speed, dir_unit) vr2 = dot(ball2.speed, dir_unit) dvr = vr2 - vr1 #logging.debug(('dist', dist, 'newdist', newdist, 'newdvr', dot(ball1.speed-ball2.speed,dir_unit))) return True else: return False else: return False def collide_cue(self, cue): r = self.radius irect = cue.rect ball = None headondist = 100000 for i, b in enumerate(self.ballsprites.sprites()): cuespeed_unit = cue.speed / hypot(*cue.speed) tip = irect.center + cue.CUE_LENGTH / 2.0 * cuespeed_unit r21 = b.rect.center - tip r21next = b.rect.center - (tip + cue.speed) newheadondist = dot(cuespeed_unit, r21) #if dot(r21,r21next) < 0: if True: if hypot(*(r21 - dot(cuespeed_unit, r21) * cuespeed_unit)) < r and abs(dot(cuespeed_unit, r21)) < hypot(*cue.speed): if newheadondist < headondist: headondist = newheadondist ball = b if ball is None: return False tip = irect.center + cue.CUE_LENGTH / 2.0 * (cue.speed / hypot(*cue.speed)) r21 = array((ball.rect.center[0] - tip[0], ball.rect.center[1] - tip[1])) dist = hypot(*r21) #print irect, ball.rect.center, r21 ball.speed = cue.speed * 0.6 cue.speed[:] = 0.0 self.collidecue_sound.play() return True def launch_ball(self, mouse_src): # making all other previous Cues disappear and making a new one if not len(self.cuesprite.sprites()) == 0: self.cuesprite.empty() self.cuesprite.add(Cue(self)) #init_rect = self.cuesprite.sprites()[0].rect mousepressed = True # remains True till the mouse is held down self.cuesprite.clear(self.screen, self.background) self.cuesprite.update(pygame.mouse.get_pos(), mousepressed) self.draw() while mousepressed: e = pygame.event.poll() if e.type == MOUSEMOTION: self.cuesprite.clear(self.screen, self.background) self.cuesprite.update(pygame.mouse.get_pos(), mousepressed) self.draw() if e.type == MOUSEBUTTONUP: #logging.debug('mouse released') mousepressed = False self.cuesprite.update(pygame.mouse.get_pos(), mousepressed) self.start_game() def allsleeping(self): for ball in self.ballsprites.sprites(): if hypot(*ball.speed) > self.friction: return False return True def on_allsleeping(self): if not self.whiteball in self.ballsprites.sprites(): whiteball = Ball(array([self.width / 2.0, self.height / 2.0]), self, is_white=True) self.whiteball = whiteball self.ballsprites.add(whiteball) self.scoreboard.set_new_active_player() if not self.new_player_set: self.scoreboard.set_active_player(self.scoreboard.new_active_player) self.new_player_set = True def start_game(self): self.RUNNING = True self.runningballs = False t = time.time() #1268749892.305392 while self.RUNNING == True: t2 = time.time() #print 'FPS :', 1/(t2-t) t = t2 time.sleep(self.wait) self.after_one_timestep() for event in pygame.event.get(): if event.type == KEYUP and event.key == K_SPACE and self.RUNNING == True: self.pause_game() if event.type == KEYDOWN and event.key == K_s: self.wait += 0.01 # see in slow motion if event.type == KEYDOWN and event.key == K_f: if self.wait < 0.02: print "Running at normal speed. Can't speed up." else: self.wait -= 0.01 # see in fast motion (can't be faster than normal speed) if event.type == KEYDOWN and event.key == K_r: self.wait = 0.01 # reset to normal speed if event.type == KEYDOWN and event.key == K_q: sys.exit(0) if event.type == KEYDOWN and event.key == K_RETURN: pygame.display.toggle_fullscreen() if event.type == KEYDOWN and event.key == K_n: #print 'new game' for player in self.players: player.score = 0 player.is_active = False self.scoreboard.set_active_player(self.players[0]) self.ballsprites.empty() self.generate_balls() if event.type == MOUSEBUTTONDOWN: self.new_player_set = False self.scoreboard.set_active_player(self.scoreboard.new_active_player) self.scoreboard.set_new_active_player() self.initscores = [player.score for player in self.players] if self.replaying: self.wait = 0.01 self.replaying = False mouse_src = pygame.mouse.get_pos() self.launch_ball(mouse_src) if event.type == KEYDOWN and event.key == K_e: self.replaying = True self.wait = 0.03 self.ballsprites.empty() self.generate_balls(self.initballpos, self.initballspeed) self.cuesprite.sprites()[0].speed = self.initcuespeed self.cuesprite.sprites()[0].rect.topleft = self.inittopleft self.cuesprite.update(None, False) self.scoreboard.set_scores(self.initscores) self.start_game() if event.type == KEYDOWN and event.key == K_d: pdb.set_trace() if event.type == QUIT: sys.exit(0) if self.allsleeping(): self.on_allsleeping() if len(self.ballsprites.sprites()) == 1 and self.ballsprites.sprites()[0] == self.whiteball: if self.runningballs: if not pygame.mixer.get_busy(): self.finishmessage.play() logging.info('Game Over') self.runningballs = False while self.RUNNING == False: event = pygame.event.poll() if event.type == MOUSEBUTTONDOWN: mouse_src = pygame.mouse.get_pos() self.launch_ball(mouse_src) def pause_game(self): self.RUNNING = False while self.RUNNING == False: for event in pygame.event.get(): if event.type == KEYUP and event.key == K_SPACE: self.RUNNING = True self.start_game() elif event.type == KEYDOWN and event.key == K_q: sys.exit(0) elif event.type == MOUSEBUTTONDOWN: mouse_src = pygame.mouse.get_pos() self.launch_ball(mouse_src) def run(self): for event in pygame.event.get(): if event.type == KEYUP and event.key == K_SPACE: for ball in self.ballsprites.sprites(): ball.speed = array([-self.VEL_MAX * (2 * random.random() - 1), self.VEL_MAX * (2 * random.random() - 1)]) #ball.speed = self.VEL_MAX * (2*random.randn(2)-1) self.start_game() elif event.type == QUIT: return False elif event.type == KEYDOWN and event.key == K_q: return False elif event.type == MOUSEBUTTONDOWN: mouse_src = pygame.mouse.get_pos() self.launch_ball(mouse_src) return True def main(): game = Billiards() while game.run(): pass if __name__ == '__main__': main()
Python
# -*- coding: utf-8 -*- import pygame, sys, os, random from pygame.locals import * import time from math import * from numpy import * from settings import logging if not pygame.font: print "Warning, fonts disabled!" if not pygame.mixer: print "Warning, sounds disabled!" RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) YELLOW = (255, 255, 0) mod = lambda v: sqrt(v[0]*v[0] + v[1]*v[1]) class Ball(pygame.sprite.Sprite): def __init__(self, pos, board, vel=array([0.0,0.0]), is_white=False): pygame.sprite.Sprite.__init__(self) self.board = board self.is_white = is_white if self.is_white: self.image = self.board.theme.get_ball(0) else: self.image = self.board.theme.get_ball() self.rect = self.image.get_rect() pos = array(pos) self.rect.center = pos self.speed = vel self.initspeed = vel.copy() self.radius = int(self.rect.width / 2.0 + 1.0) self.pos = pos def draw(self): self.board.screen.blit(self.image, self.rect) pygame.display.flip() def set_pos(self, pos): self.pos = pos #self.rect.clamp_ip(to_int([pos[0]-self.pos[0], pos[1]-self.pos[1]])) #self.myrect = Rect(self.pos,(1,1)) #self.rect.clamp_ip(self.myrect) self.rect.center = self.pos def decelerate(self, friction): if mod(self.speed) <= friction: self.speed = array([0.0,0.0]) else: self.speed[0] = self.speed[0] - friction * self.speed[0] / mod(self.speed) # friction acts in a direction self.speed[1] = self.speed[1] - friction * self.speed[1] / mod(self.speed) # opposite to velocity def reflect(self): reflected = False if self.rect.left < 0 or self.rect.right > self.board.width: reflected = True self.speed[0] = -self.speed[0] if self.rect.left < 0: self.set_pos(array([self.radius, self.rect.center[1]])) else: self.set_pos(array([self.board.width - self.radius, self.rect.center[1]])) elif self.rect.top < 0 or self.rect.bottom > self.board.height: reflected = True self.speed[1] = -self.speed[1] if self.rect.top < 0: self.set_pos(array([self.rect.center[0], self.radius])) else: self.set_pos(array([self.rect.center[0], self.board.height - self.radius])) if reflected: self.board.collidecue_sound.play() def collide(self): ''' Collides current ball with other balls of the board if possible. ''' otherballs = self.board.ballsprites.sprites()[:] otherballs.remove(self) # otherballs are all balls except *this* ball if len(otherballs) == 0: pass # no ball to collide with else: for otherball in otherballs: self.board.collide_ball(self, otherball) def go_to_holes(self): for hole in self.board.holerectlist: if hypot(*(self.rect.center-array(hole.center))) < 0.5*self.board.hole_radius: if self == self.board.whiteball: print self.board.scoreboard.active_player.name,'fouled' else: print self.board.scoreboard.active_player.name,'scored' self.board.gotoholes_sound.play() self.board.ballsprites.remove(self) # remove that ball from the game self.board.scoreboard.update(ball=self) # update the score self.board.scoreboard.new_active_player = self.board.scoreboard.active_player def update(self, change=None, dest=None): ''' Updates the position of current ball on the board according to the current speed and whether it reflects or collides with other balls (default action). If 'change' is specified, moves the ball by that change vector. If 'dest' is specified, moves the ball to the position specified by 'dest'. ''' self.reflect() # reflects from board walls if possible self.collide() # collides with other balls if possible self.go_to_holes() # goes to holes if possible self.decelerate(self.board.friction) # decelerates due to surface friction if change == None: change = self.speed if dest == None: self.set_pos(self.pos+change) else: self.rect.center = dest
Python
# -*- coding: utf-8 -*- import logging import os import pygame from settings import settings class Theme(object): '''A class to implement themes in pybilliards All other objects using any data must request it from a theme ''' def __init__(self, setting=None, name=None, path=None): if setting is None: setting = settings self.settings = setting if name is None: name = setting.get('theme') if name is None: name = 'default' if path is None: for f in setting.get('defaultdatadir'),setting.get('systemdatadir'),setting.get('userdatadir'): if os.path.isdir(f) and os.path.isdir(os.path.join(f,'themes')) and name in os.listdir(os.path.join(f,'themes')): path = os.path.join(f,'themes',name) break if path is None: logging.warn('Theme "%s" not found: using "default"'%name) name = 'default' path = os.path.join(setting.get('defaultdatadir'),'themes',name) self.name = name self.path = path def get_ball(self, ballnum=-1): '''get the ball image for specified ball number if the specified ball number is not exported by a theme the default ball of the theme is returned ballnum=0 is used as a convention for the striker ball''' suffix = str(ballnum) if ballnum >= 0 else '' suffix = suffix + '.png' try: ret = pygame.image.load(os.path.join(self.path,'ball%s'%suffix)) except: logging.info('Theme "%s" does not provide ball%d: using default'%(self.name,ballnum)) ret = pygame.image.load(os.path.join(self.path,'ball.png')) ret.convert_alpha() return ret def get_cue(self): ret = pygame.image.load(os.path.join(self.path,'cue.png')) ret.convert_alpha() return ret def get_background(self): ret = pygame.image.load(os.path.join(self.path,'background.png')) ret.convert_alpha() return ret def get_collide_snd(self): return pygame.mixer.Sound(os.path.join(self.path,'collide.ogg')) def get_gotoholes_snd(self): return pygame.mixer.Sound(os.path.join(self.path,'gotoholes.ogg')) def get_finish_snd(self): return pygame.mixer.Sound(os.path.join(self.path,'finish.ogg')) def get(self, name): '''A convenience method to get image and sound objects from a theme and provide extensible theme support''' ext = name.split(os.path.extsep) ext = ext[-1] if len(ext)>1 else '' if ext == 'png': ret = pygame.image.load(os.path.join(self.path,name)) ret.convert_alpha() elif ext == 'ogg': ret = pygame.mixer.Sound(os.path.join(self.path,name)) else: ret = open(os.path.join(self.path,name)) return ret def __getitem__(self, name): return self.get(name) def get_theme(name=None): if name is None: theme = Theme(settings, settings.get('theme')) else: try: theme = __import__('data.themes.%s'%name,fromlist='Theme') theme = theme(settings, name) except ImportError: logging.info('cannot find theme: %s'%theme) theme = Theme(settings) return theme
Python
# The default system settings import os __datadir = os.path.join(os.path.dirname(__file__),'data') if not os.path.exists(__datadir): import sys try: if sys.frozen == 1: # for executables built using pyinstaller try: __datadir = os.path.join(os.environ['_MEIPASS2'], 'data') except KeyError: __datadir = os.path.join(os.path.dirname(sys.executable), 'data') except AttributeError: pass settings = {'defaultdatadir': __datadir, 'systemdatadir' : os.path.join('/etc','pybilliards','data'), 'userdatadir' : os.path.join(os.path.expanduser('~'),'.config','pybilliards','data'), 'userdir' : os.path.join(os.path.expanduser('~'),'.config','pybilliards'), 'loglevel' : 'debug', 'theme' : 'default', }
Python
print 'Content-Type: text/plain' print '' print 'You probably want /tetris ...'
Python
import cgi import datetime import urllib import wsgiref.handlers import random import datetime from django.utils import simplejson from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class Score(db.Model): name=db.StringProperty() score=db.IntegerProperty() date=db.StringProperty() tempRef=db.IntegerProperty() class HSPostGameHandler(webapp.RequestHandler): def post(self): myScoreQ = db.GqlQuery("SELECT * FROM Score " + "WHERE tempRef = %s" % (self.request.get('tempRef'))) myScore = myScoreQ[0] dailyRankQ = db.GqlQuery("SELECT * FROM Score WHERE date = '%s' AND score > %s" % (myScore.date, myScore.score)) dailyRank = len(dailyRankQ.fetch(1000)) + 1 if dailyRank > 100: dailyRank = -1 self.response.out.write(simplejson.dumps({ 'userScore': myScore.score, 'tempRef': myScore.tempRef, 'dailyRank': dailyRank }) + '\n'); class HSReportScoreHandler(webapp.RequestHandler): def post(self): # TODO: make a real anti-fake-score-abuse system # don't care about abuse, blowing away long-term score storage score = int(self.request.get('gthbyu'))/17 tempRef = int(random.random() * 100000000) # TODO: CGI clean name input record = Score(score=score, name=cgi.escape(self.request.get('name') or 'Unnamed'), tempRef=tempRef, date=datetime.date.today().isoformat()) record.put() self.response.out.write(str(tempRef) + '\n') class HSApplyNameHandler(webapp.RequestHandler): def post(self): tempRef = self.request.get('tempRef') name = self.request.get('name') scoreQ = db.GqlQuery("SELECT * FROM Score WHERE tempRef = %s" % tempRef) score = scoreQ[0] score.name = name score.tempRef = 0 score.put() class HSTablesHandler(webapp.RequestHandler): def post(self): # get both lists topScoreQ = db.GqlQuery("SELECT * FROM Score ORDER BY score DESC") topScores = topScoreQ.fetch(100) todayString = datetime.date.today().isoformat() dailyScoreQ = db.GqlQuery("SELECT * FROM Score WHERE date = '%s' ORDER By score DESC" % (todayString)) dailyScores = dailyScoreQ.fetch(100) topScoreList = [] dailyScoreList = [] # remove the unneeded values from the lists for curScore in topScores: topScoreList.append({ 'score': curScore.score, 'date': curScore.date, 'name': curScore.name }) for curScore in dailyScores: dailyScoreList.append({ 'score': curScore.score, 'name': curScore.name }) self.response.out.write(simplejson.dumps({ 'topScores': topScoreList, 'dailyScores': dailyScoreList })); class HSPurgeHandler(webapp.RequestHandler): def get(self): topScoreQ = db.GqlQuery("SELECT * FROM Score ORDER BY score DESC") topScores = topScoreQ.fetch(100) todayString = datetime.date.today().isoformat() dailyScoreQ = db.GqlQuery("SELECT * FROM Score WHERE date = '%s' ORDER By score DESC" % (todayString)) dailyScores = dailyScoreQ.fetch(100) keepSet = set() for score in topScores: keepSet.add(score.key()) for score in dailyScores: keepSet.add(score.key()) allScores = db.GqlQuery("SELECT * FROM Score") # remove the values that are not in the top 100 or daily 100 for score in allScores: if score.key() not in keepSet: score.delete() application = webapp.WSGIApplication([ ('/score/postGame', HSPostGameHandler), ('/score/reportScore', HSReportScoreHandler), ('/score/apply', HSApplyNameHandler), ('/score/tables', HSTablesHandler), ('/score/purge', HSPurgeHandler) ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
Python
# If you're reading this, you're doing it wrong. from random import randint,shuffle print("Philip Daian's Vocab Review Program\nhttp://nerd.nu/, licensed under GPL.") reverse = raw_input("\nReverse or normal mode? ").lower() if "reverse" in reverse: print "Reverse mode. Definitions will show first." reverse = True else: print "Normal mode." reverse = False try: vocab = open("vocab.txt").read().splitlines() except: print("Error. Make sure the file vocab.txt is in the same directory as this script.") vocab = [x.split("^^",1) for x in vocab] shuffle(vocab) while True: if len(vocab) == 0: break whee = vocab.pop() if reverse: whee.reverse() print(whee[0]) if reverse: raw_input("Press return to view the word.") else: raw_input("Press return to view the definition") print '_____________\n\n', whee[1], '\n_____________\n' answer = raw_input("Did you get it? Type y or n. ") if "y" in answer: print "Okay. Removing from stack.","\n"*3 else: print "Keeping in stack.", "\n"*3 if len(vocab)>3: vocab.insert(randint(0, len(vocab)-2), whee) else: vocab.insert(randint(0,len(vocab)),whee) raw_input("Congrats, you finished. Bye!")
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 21:54:45 CST 2009 def mainflow(): n = input() for i in range(n): if i > 0: raw_input() m = input() alist = [] for j in range(m): line = raw_input() alist.append(line) alist.sort() last = alist[0] count = 0 for j in range(1, m): if alist[j] == last: count += 1 else: print last, count last = alist[j] count = 1 print last, count print mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 21:54:45 CST 2009 def mainflow(): n = input() for i in range(n): if i > 0: raw_input() m = input() alist = [] for j in range(m): line = raw_input() alist.append(line) alist.sort() last = alist[0] count = 0 for j in range(1, m): if alist[j] == last: count += 1 else: print last, count last = alist[j] count = 1 print last, count print mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 24 06:14:08 PM CST 2009 def foo(a, b): a = int(''.join(reversed(str(a)))) b = int(''.join(reversed(str(b)))) return int(''.join(reversed(str(a+b)))) def test(): assert foo(24,1) == 34 assert foo(305, 794) == 1 test() n = input() while n > 0: n -= 1 a, b = raw_input().split() a, b = int(a), int(b) print foo(a, b)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 05:18:35 PM CST 2009 def Z(num): r = 0 while num > 0: num /= 5 r += num print r def mainflow(): n = input() for i in range(n): num = input() Z(num) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 25 06:09:25 PM CST 2009 def foo(s): m = 1 ms = s for i in range(1, len(s)): s = s[1:] + s[0] #print 'ms=',ms, 's=', s if s < ms: ms = s m = i+1 #print 'ms=', ms, 'm=', m return m def test(): assert foo('helloworld')==10 assert foo('amandamanda')==11 assert foo('aaabaaa')==5 assert foo('dontcallmebfu')==6 test() n = input() while n > 0: n -= 1 print foo(raw_input())
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 21:54:45 CST 2009 def mainflow(): n = input() for i in range(n): if i > 0: raw_input() m = input() alist = [] for j in range(m): line = raw_input() alist.append(line) alist.sort() last = alist[0] count = 0 for j in range(1, m): if alist[j] == last: count += 1 else: print last, count last = alist[j] count = 1 print last, count print mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 22:43:40 CST 2009 from bisect import * import random def get_seeds(max): roots=(4,7) seeds=[] for i in range(1, max+1): for j in range(0, 2**i): n = j m = 0 for k in range(i): m *= 10 m += roots[j % 2] j /= 2 #print m seeds.append(m); seeds.sort() #print seeds return seeds def naive(max): seeds = get_seeds(max) maxn = 10**max size = len(seeds) result = seeds while True: #print size result += [a*b for a in result for b in result if a*b<=maxn] #print result result = list(set(result)) if len(result) == size: result.sort() return result size = len(result) def lucky_number(max): seeds = get_seeds(max) maxn = 10**max result = set() v = [1] for s in seeds: #print len(result) #if s * s > maxn: break print 's=', s a = v while a: b = [] for i in a: if i*s > maxn: break #if i*s in result: continue b.append(i*s) result.add(i*s) #print "a=", a print "b=", b v += b a = b #result.sort() #print result v.sort() v = v[:bisect(v, maxn/s)] #print v result = list(result) result.sort() return result def mainflow(): r = lucky_number(9) #print len(r), len(naive(4)) #print ' '.join(map(str, naive(3))) #print len(naive(3)); return #print r #print ' '.join(map(str, r)) print len(r);return #print naive(3) #return n = input() for i in range(n): #a, b = map(int, raw_input().split()) #a = random.randint(0, 10**12) a = 0 b = random.randint(a, 10**12) print a, b print bisect(r, b) - bisect_left(r, a) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 19 10:21:12 AM CST 2009 import math def primes(m): pp = range(2, m+1) p = [] while pp[0] ** 2 <= m: p.append(pp[0]) pp = [e for e in pp if e % pp[0] != 0] p.extend(pp) return p def func(a, b): if a < 2: a =2 ps = primes(int(math.sqrt(b)) + 1) nn = range(a, b+1) flag = [True] * (b-a+1) for p in ps: s = (a-1)/p*p + p for j in range(max(p*2, s), b+1, p): if j%p == 0: flag[j-a] = False for n in nn: if flag[n-a]: print n print def mainflow(): n = input() for i in range(n): a, b = raw_input().split() func(int(a), int(b)) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 18 05:18:37 PM CST 2009 def fun(num): cnt = 0 for i in xrange(0, 4**num): a = [] s = i for j in xrange(0, num): a.append(s%4) s /= 4 if a.count(0) % 2 == 0 and a.count(1) % 2 == 0: #print 'y', cnt += 1 #print a #else:print 'n', #print i, a return cnt s={} def fun2(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun2(num-1, r)*2 + fun2(num-1, 1)*2 else: re = fun2(num-1, r)*2 + fun2(num-1, 0) + fun2(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) s[(num, r)] = re return re def fun3(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun3(num-1, r)*2 + fun3(num-1, 1)*2 else: re = fun3(num-1, r)*2 + fun3(num-1, 0) + fun3(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re def fun4(num, r = 0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0: if num % 2 == 0: re = fun4(num/2)**2 + fun4(num/2, 1)**2*2 + fun4(num/2, 2)**2 else: re = 2*fun4(num-1, 0) + 2*fun4(num-1, 1) elif r == 2: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 2)*2 + fun4(num/2, 1)**2*2 else: re = 2*fun4(num-1, 2) + 2*fun4(num-1, 1) elif r == 1: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 1) * 2 + fun4(num/2, 1)*fun4(num/2, 2)*2 else: re = 2*fun4(num-1, 1) + fun4(num-1, 0) + fun4(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re fun4(2) for n in range(1,9): #print n #break s= {} #print fun(n), fun2(n) #print fun2(n) % 10007 , #print fun4(n), len(s) #s = {} print n, fun4(n), len(s) for n in range(999999990, 1000000000): print n, fun4(n) #print fun3(99999) #print fun3(5) #print fun4(5)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 19 10:21:12 AM CST 2009 import math def primes(m): pp = range(2, m+1) p = [] while pp[0] ** 2 <= m: p.append(pp[0]) pp = [e for e in pp if e % pp[0] != 0] p.extend(pp) return p def func(a, b): if a < 2: a =2 ps = primes(int(math.sqrt(b)) + 1) nn = range(a, b+1) flag = [True] * (b-a+1) for p in ps: s = (a-1)/p*p + p for j in range(max(p*2, s), b+1, p): if j%p == 0: flag[j-a] = False for n in nn: if flag[n-a]: print n print def mainflow(): n = input() for i in range(n): a, b = raw_input().split() func(int(a), int(b)) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 22:43:40 CST 2009 from bisect import * import random def get_seeds(max): roots=(4,7) seeds=[] for i in range(1, max+1): for j in range(0, 2**i): n = j m = 0 for k in range(i): m *= 10 m += roots[j % 2] j /= 2 #print m seeds.append(m); seeds.sort() #print seeds return seeds def naive(max): seeds = get_seeds(max) maxn = 10**max size = len(seeds) result = seeds while True: #print size result += [a*b for a in result for b in result if a*b<=maxn] #print result result = list(set(result)) if len(result) == size: result.sort() return result size = len(result) def lucky_number(max): seeds = get_seeds(max) maxn = 10**max result = set() v = [1] for s in seeds: #print len(result) #if s * s > maxn: break print 's=', s a = v while a: b = [] for i in a: if i*s > maxn: break #if i*s in result: continue b.append(i*s) result.add(i*s) #print "a=", a print "b=", b v += b a = b #result.sort() #print result v.sort() v = v[:bisect(v, maxn/s)] #print v result = list(result) result.sort() return result def mainflow(): r = lucky_number(9) #print len(r), len(naive(4)) #print ' '.join(map(str, naive(3))) #print len(naive(3)); return #print r #print ' '.join(map(str, r)) print len(r);return #print naive(3) #return n = input() for i in range(n): #a, b = map(int, raw_input().split()) #a = random.randint(0, 10**12) a = 0 b = random.randint(a, 10**12) print a, b print bisect(r, b) - bisect_left(r, a) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 18 05:18:37 PM CST 2009 def fun(num): cnt = 0 for i in xrange(0, 4**num): a = [] s = i for j in xrange(0, num): a.append(s%4) s /= 4 if a.count(0) % 2 == 0 and a.count(1) % 2 == 0: #print 'y', cnt += 1 #print a #else:print 'n', #print i, a return cnt s={} def fun2(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun2(num-1, r)*2 + fun2(num-1, 1)*2 else: re = fun2(num-1, r)*2 + fun2(num-1, 0) + fun2(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) s[(num, r)] = re return re def fun3(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun3(num-1, r)*2 + fun3(num-1, 1)*2 else: re = fun3(num-1, r)*2 + fun3(num-1, 0) + fun3(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re def fun4(num, r = 0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0: if num % 2 == 0: re = fun4(num/2)**2 + fun4(num/2, 1)**2*2 + fun4(num/2, 2)**2 else: re = 2*fun4(num-1, 0) + 2*fun4(num-1, 1) elif r == 2: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 2)*2 + fun4(num/2, 1)**2*2 else: re = 2*fun4(num-1, 2) + 2*fun4(num-1, 1) elif r == 1: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 1) * 2 + fun4(num/2, 1)*fun4(num/2, 2)*2 else: re = 2*fun4(num-1, 1) + fun4(num-1, 0) + fun4(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re fun4(2) for n in range(1,9): #print n #break s= {} #print fun(n), fun2(n) #print fun2(n) % 10007 , #print fun4(n), len(s) #s = {} print n, fun4(n), len(s) for n in range(999999990, 1000000000): print n, fun4(n) #print fun3(99999) #print fun3(5) #print fun4(5)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 24 06:14:08 PM CST 2009 def foo(a, b): a = int(''.join(reversed(str(a)))) b = int(''.join(reversed(str(b)))) return int(''.join(reversed(str(a+b)))) def test(): assert foo(24,1) == 34 assert foo(305, 794) == 1 test() n = input() while n > 0: n -= 1 a, b = raw_input().split() a, b = int(a), int(b) print foo(a, b)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 25 06:09:25 PM CST 2009 def foo(s): m = 1 ms = s for i in range(1, len(s)): s = s[1:] + s[0] #print 'ms=',ms, 's=', s if s < ms: ms = s m = i+1 #print 'ms=', ms, 'm=', m return m def test(): assert foo('helloworld')==10 assert foo('amandamanda')==11 assert foo('aaabaaa')==5 assert foo('dontcallmebfu')==6 test() n = input() while n > 0: n -= 1 print foo(raw_input())
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 05:18:35 PM CST 2009 def Z(num): r = 0 while num > 0: num /= 5 r += num print r def mainflow(): n = input() for i in range(n): num = input() Z(num) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 24 06:14:08 PM CST 2009 def foo(a, b): a = int(''.join(reversed(str(a)))) b = int(''.join(reversed(str(b)))) return int(''.join(reversed(str(a+b)))) def test(): assert foo(24,1) == 34 assert foo(305, 794) == 1 test() n = input() while n > 0: n -= 1 a, b = raw_input().split() a, b = int(a), int(b) print foo(a, b)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 05:18:35 PM CST 2009 def Z(num): r = 0 while num > 0: num /= 5 r += num print r def mainflow(): n = input() for i in range(n): num = input() Z(num) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 25 06:09:25 PM CST 2009 def foo(s): m = 1 ms = s for i in range(1, len(s)): s = s[1:] + s[0] #print 'ms=',ms, 's=', s if s < ms: ms = s m = i+1 #print 'ms=', ms, 'm=', m return m def test(): assert foo('helloworld')==10 assert foo('amandamanda')==11 assert foo('aaabaaa')==5 assert foo('dontcallmebfu')==6 test() n = input() while n > 0: n -= 1 print foo(raw_input())
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 21:54:45 CST 2009 def mainflow(): n = input() for i in range(n): if i > 0: raw_input() m = input() alist = [] for j in range(m): line = raw_input() alist.append(line) alist.sort() last = alist[0] count = 0 for j in range(1, m): if alist[j] == last: count += 1 else: print last, count last = alist[j] count = 1 print last, count print mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 22:43:40 CST 2009 from bisect import * import random def get_seeds(max): roots=(4,7) seeds=[] for i in range(1, max+1): for j in range(0, 2**i): n = j m = 0 for k in range(i): m *= 10 m += roots[j % 2] j /= 2 #print m seeds.append(m); seeds.sort() #print seeds return seeds def naive(max): seeds = get_seeds(max) maxn = 10**max size = len(seeds) result = seeds while True: #print size result += [a*b for a in result for b in result if a*b<=maxn] #print result result = list(set(result)) if len(result) == size: result.sort() return result size = len(result) def lucky_number(max): seeds = get_seeds(max) maxn = 10**max result = set() v = [1] for s in seeds: #print len(result) #if s * s > maxn: break print 's=', s a = v while a: b = [] for i in a: if i*s > maxn: break #if i*s in result: continue b.append(i*s) result.add(i*s) #print "a=", a print "b=", b v += b a = b #result.sort() #print result v.sort() v = v[:bisect(v, maxn/s)] #print v result = list(result) result.sort() return result def mainflow(): r = lucky_number(9) #print len(r), len(naive(4)) #print ' '.join(map(str, naive(3))) #print len(naive(3)); return #print r #print ' '.join(map(str, r)) print len(r);return #print naive(3) #return n = input() for i in range(n): #a, b = map(int, raw_input().split()) #a = random.randint(0, 10**12) a = 0 b = random.randint(a, 10**12) print a, b print bisect(r, b) - bisect_left(r, a) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 19 10:21:12 AM CST 2009 import math def primes(m): pp = range(2, m+1) p = [] while pp[0] ** 2 <= m: p.append(pp[0]) pp = [e for e in pp if e % pp[0] != 0] p.extend(pp) return p def func(a, b): if a < 2: a =2 ps = primes(int(math.sqrt(b)) + 1) nn = range(a, b+1) flag = [True] * (b-a+1) for p in ps: s = (a-1)/p*p + p for j in range(max(p*2, s), b+1, p): if j%p == 0: flag[j-a] = False for n in nn: if flag[n-a]: print n print def mainflow(): n = input() for i in range(n): a, b = raw_input().split() func(int(a), int(b)) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 18 05:18:37 PM CST 2009 def fun(num): cnt = 0 for i in xrange(0, 4**num): a = [] s = i for j in xrange(0, num): a.append(s%4) s /= 4 if a.count(0) % 2 == 0 and a.count(1) % 2 == 0: #print 'y', cnt += 1 #print a #else:print 'n', #print i, a return cnt s={} def fun2(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun2(num-1, r)*2 + fun2(num-1, 1)*2 else: re = fun2(num-1, r)*2 + fun2(num-1, 0) + fun2(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) s[(num, r)] = re return re def fun3(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun3(num-1, r)*2 + fun3(num-1, 1)*2 else: re = fun3(num-1, r)*2 + fun3(num-1, 0) + fun3(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re def fun4(num, r = 0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0: if num % 2 == 0: re = fun4(num/2)**2 + fun4(num/2, 1)**2*2 + fun4(num/2, 2)**2 else: re = 2*fun4(num-1, 0) + 2*fun4(num-1, 1) elif r == 2: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 2)*2 + fun4(num/2, 1)**2*2 else: re = 2*fun4(num-1, 2) + 2*fun4(num-1, 1) elif r == 1: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 1) * 2 + fun4(num/2, 1)*fun4(num/2, 2)*2 else: re = 2*fun4(num-1, 1) + fun4(num-1, 0) + fun4(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re fun4(2) for n in range(1,9): #print n #break s= {} #print fun(n), fun2(n) #print fun2(n) % 10007 , #print fun4(n), len(s) #s = {} print n, fun4(n), len(s) for n in range(999999990, 1000000000): print n, fun4(n) #print fun3(99999) #print fun3(5) #print fun4(5)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 19 10:21:12 AM CST 2009 import math def primes(m): pp = range(2, m+1) p = [] while pp[0] ** 2 <= m: p.append(pp[0]) pp = [e for e in pp if e % pp[0] != 0] p.extend(pp) return p def func(a, b): if a < 2: a =2 ps = primes(int(math.sqrt(b)) + 1) nn = range(a, b+1) flag = [True] * (b-a+1) for p in ps: s = (a-1)/p*p + p for j in range(max(p*2, s), b+1, p): if j%p == 0: flag[j-a] = False for n in nn: if flag[n-a]: print n print def mainflow(): n = input() for i in range(n): a, b = raw_input().split() func(int(a), int(b)) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 22:43:40 CST 2009 from bisect import * import random def get_seeds(max): roots=(4,7) seeds=[] for i in range(1, max+1): for j in range(0, 2**i): n = j m = 0 for k in range(i): m *= 10 m += roots[j % 2] j /= 2 #print m seeds.append(m); seeds.sort() #print seeds return seeds def naive(max): seeds = get_seeds(max) maxn = 10**max size = len(seeds) result = seeds while True: #print size result += [a*b for a in result for b in result if a*b<=maxn] #print result result = list(set(result)) if len(result) == size: result.sort() return result size = len(result) def lucky_number(max): seeds = get_seeds(max) maxn = 10**max result = set() v = [1] for s in seeds: #print len(result) #if s * s > maxn: break print 's=', s a = v while a: b = [] for i in a: if i*s > maxn: break #if i*s in result: continue b.append(i*s) result.add(i*s) #print "a=", a print "b=", b v += b a = b #result.sort() #print result v.sort() v = v[:bisect(v, maxn/s)] #print v result = list(result) result.sort() return result def mainflow(): r = lucky_number(9) #print len(r), len(naive(4)) #print ' '.join(map(str, naive(3))) #print len(naive(3)); return #print r #print ' '.join(map(str, r)) print len(r);return #print naive(3) #return n = input() for i in range(n): #a, b = map(int, raw_input().split()) #a = random.randint(0, 10**12) a = 0 b = random.randint(a, 10**12) print a, b print bisect(r, b) - bisect_left(r, a) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 18 05:18:37 PM CST 2009 def fun(num): cnt = 0 for i in xrange(0, 4**num): a = [] s = i for j in xrange(0, num): a.append(s%4) s /= 4 if a.count(0) % 2 == 0 and a.count(1) % 2 == 0: #print 'y', cnt += 1 #print a #else:print 'n', #print i, a return cnt s={} def fun2(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun2(num-1, r)*2 + fun2(num-1, 1)*2 else: re = fun2(num-1, r)*2 + fun2(num-1, 0) + fun2(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) s[(num, r)] = re return re def fun3(num, r=0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0 or r == 2: re = fun3(num-1, r)*2 + fun3(num-1, 1)*2 else: re = fun3(num-1, r)*2 + fun3(num-1, 0) + fun3(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re def fun4(num, r = 0): if (num, r) in s: return s[(num, r)] if r == num: re = max(r, 1) elif num < r: re = 0 elif r == 0: if num % 2 == 0: re = fun4(num/2)**2 + fun4(num/2, 1)**2*2 + fun4(num/2, 2)**2 else: re = 2*fun4(num-1, 0) + 2*fun4(num-1, 1) elif r == 2: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 2)*2 + fun4(num/2, 1)**2*2 else: re = 2*fun4(num-1, 2) + 2*fun4(num-1, 1) elif r == 1: if num % 2 == 0: re = fun4(num/2)*fun4(num/2, 1) * 2 + fun4(num/2, 1)*fun4(num/2, 2)*2 else: re = 2*fun4(num-1, 1) + fun4(num-1, 0) + fun4(num-1, 2) #print 'num=%d r=%d result=%d'%(num, r, re) re %= 10007 s[(num, r)] = re return re fun4(2) for n in range(1,9): #print n #break s= {} #print fun(n), fun2(n) #print fun2(n) % 10007 , #print fun4(n), len(s) #s = {} print n, fun4(n), len(s) for n in range(999999990, 1000000000): print n, fun4(n) #print fun3(99999) #print fun3(5) #print fun4(5)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 24 06:14:08 PM CST 2009 def foo(a, b): a = int(''.join(reversed(str(a)))) b = int(''.join(reversed(str(b)))) return int(''.join(reversed(str(a+b)))) def test(): assert foo(24,1) == 34 assert foo(305, 794) == 1 test() n = input() while n > 0: n -= 1 a, b = raw_input().split() a, b = int(a), int(b) print foo(a, b)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 25 06:09:25 PM CST 2009 def foo(s): m = 1 ms = s for i in range(1, len(s)): s = s[1:] + s[0] #print 'ms=',ms, 's=', s if s < ms: ms = s m = i+1 #print 'ms=', ms, 'm=', m return m def test(): assert foo('helloworld')==10 assert foo('amandamanda')==11 assert foo('aaabaaa')==5 assert foo('dontcallmebfu')==6 test() n = input() while n > 0: n -= 1 print foo(raw_input())
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 20 05:18:35 PM CST 2009 def Z(num): r = 0 while num > 0: num /= 5 r += num print r def mainflow(): n = input() for i in range(n): num = input() Z(num) mainflow()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 30 08:25:22 CST 2008 import sys, Ice, traceback, time sys.path.append('ice') import fk class WorkerI(fk.Worker): def work(self, cmd, data, current=None): #sys.stdout=sys.stderr print 'cmd=%s time=%s'%(cmd, time.asctime()) if cmd == 'echo': return data else: return str(len(data)) try: status = 0 ic = Ice.initialize(sys.argv) adapter = ic.createObjectAdapterWithEndpoints("Adapter", "default -p 12345") obj = WorkerI() adapter.add(obj, Ice.stringToIdentity("Worker")) adapter.activate() ic.waitForShutdown() except: traceback.print_exc() status = 1 try: if ic: ic.destroy() except: traceback.print_exc() status = 1 sys.exit(status)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 30 06:45:14 CST 2008 import sys, Ice, traceback, time sys.path.append('ice') import fk def init_ic(str): try: ic = Ice.initialize(sys.argv) base = ic.stringToProxy(str) obj = fk.WorkerPrx.checkedCast(base) if not obj: raise RuntimeError('Invalid proxy') return obj, ic except: traceback.print_exc() def destroy_ic(ic): try: if ic: ic.destroy() except: traceback.print_exc() worker,ic = init_ic("Worker:default -p 12345") print worker.work('cmd1', 'data1') print worker.work('echo', 'fuck you') print worker.work('cmd1', 'data1') start = time.time() for i in range(64): print worker.work('transfer', ' '*1024*512) print 'spent=%f'%(time.time()-start) destroy_ic(ic)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 30 08:25:22 CST 2008 import sys, Ice, traceback, time sys.path.append('ice') import fk class WorkerI(fk.Worker): def work(self, cmd, data, current=None): #sys.stdout=sys.stderr print 'cmd=%s time=%s'%(cmd, time.asctime()) if cmd == 'echo': return data else: return str(len(data)) try: status = 0 ic = Ice.initialize(sys.argv) adapter = ic.createObjectAdapterWithEndpoints("Adapter", "default -p 12345") obj = WorkerI() adapter.add(obj, Ice.stringToIdentity("Worker")) adapter.activate() ic.waitForShutdown() except: traceback.print_exc() status = 1 try: if ic: ic.destroy() except: traceback.print_exc() status = 1 sys.exit(status)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 30 06:45:14 CST 2008 import sys, Ice, traceback, time sys.path.append('ice') import fk def init_ic(str): try: ic = Ice.initialize(sys.argv) base = ic.stringToProxy(str) obj = fk.WorkerPrx.checkedCast(base) if not obj: raise RuntimeError('Invalid proxy') return obj, ic except: traceback.print_exc() def destroy_ic(ic): try: if ic: ic.destroy() except: traceback.print_exc() worker,ic = init_ic("Worker:default -p 12345") print worker.work('cmd1', 'data1') print worker.work('echo', 'fuck you') print worker.work('cmd1', 'data1') start = time.time() for i in range(64): print worker.work('transfer', ' '*1024*512) print 'spent=%f'%(time.time()-start) destroy_ic(ic)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 26 06:33:24 CST 2008 import sys, struct def test_struct(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name fmt = 'hhl' s=struct.pack(fmt,1,2,3) print struct.unpack('il', s) buf = 'abcdef' print struct.calcsize(fmt) print struct.calcsize('xcbhilqfd') def test_stringIO(): import StringIO print '-'*48, '\nFunc:', sys._getframe().f_code.co_name output = StringIO.StringIO('joke\n') print output.getvalue() print output.tell() output.seek(0, 2) print output.tell() output.write('hello world.') print output.getvalue() output.truncate(8) print output.getvalue() print output.tell() output.seek(0) print output.readline() output.close() test_stringIO() def goodbye(name): print 'Goodbye,', name def test_atexit(): import atexit print '-'*48, '\nFunc:', sys._getframe().f_code.co_name atexit.register(goodbye, 'kevin') atexit.register(goodbye, 'kai') sys.exit(0) #test_atexit() from ctypes import * from ctypes.util import * def test_ctypes(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name cdll.LoadLibrary('libc.so.6') libc = CDLL('libc.so.6') print libc.time(0) a = c_short(5) print sizeof(a) print sizeof(c_int64) libc.printf("%p\n", addressof(a)) buf = c_buffer("joke now") libc.printf("%d %p %s\n", sizeof(buf), buf, buf) buf = create_string_buffer('joke joke') libc.printf("%d %p %s\n", sizeof(buf), buf, buf) print repr(buf.raw) print find_library('c') print find_library('db') #test_ctypes() def test_getpass(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import getpass print 'User:', getpass.getuser() p = getpass.getpass() print p #test_getpass() def test_optparse(): import optparse print '-'*48, '\nFunc:', sys._getframe().f_code.co_name parser = optparse.OptionParser(usage='%prog [options][args]', description='Fuck the world', version='%prog 1.0') parser.add_option('-f', '--file', dest='filename', help='Configuration file', metavar='FILE') parser.add_option('-g') parser.add_option('-n', type='int', dest='num', default='0', help='default = %default') parser.add_option('-v', action='store_true', dest='verbose', default=False, help='make lots of noise [default]') parser.add_option('-t', action='store', choices=['a', 'b', 'c']) g = optparse.OptionGroup(parser, 'Extra Options', 'Run on your own risk.') g.add_option('-k', help='format yourself') parser.add_option_group(g) options, args = parser.parse_args() print options #test_optparse() def test_getopt(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import getopt opts, args = getopt.getopt(sys.argv[1:], 'ab:', ['c=','bb=','d']) print 'opts:', opts print 'args:', args test_getopt() def test_tempfile(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import tempfile print tempfile.gettempprefix() print tempfile.gettempdir() print tempfile.tempdir print tempfile.mkdtemp('fk','py') print tempfile.mkstemp('fk','py') #test_tempfile() def test_robotparser(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import robotparser rp = robotparser.RobotFileParser() rp.set_url("http://www.newsmth.net/robots.txt") rp.read() print rp.can_fetch("*", "http://www.newsmth.net/") #test_robotparser() confstr = ''' [lab] room=1220 floor=2 room:1235 staff= fan, kai, kevin [lab] fake:1 ''' def test_configparser(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import ConfigParser, StringIO try: conf = ConfigParser.ConfigParser() conf.readfp(StringIO.StringIO(confstr)) print conf.has_section('lab') print conf.options('lab') print conf.items('lab') print conf.getint('lab', 'room') conf.set('lab', 'room', '1117') print conf.getint('lab', 'room') confsio = StringIO.StringIO() conf.write(confsio) print confsio.getvalue() except Exception, e: print e test_configparser() sys.stdout=sys.stderr
Python
#!/usr/bin/env python # @author FAN Kai, Peking University # @date Dec 13 18:59:18 CST 2008 import HTMLParser, htmllib, formatter, re hstr = ' '.join(open('data/any.html').read().split()) class MyHTMLParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.links = [] def handle_starttag(self, tag, attrs): if tag != 'a': return for name, value in attrs: if name == 'href' and value not in self.links: self.links.append(value) class LinkParser(htmllib.HTMLParser): def __init__(self, f): htmllib.HTMLParser.__init__(self, f) self.inside_a = False self.lastlink = '' self.links = [] self.anthor_text = '' def feed(self, data): nd = data.split('>') for i in range(0, len(nd)-1): nd[i] = nd[i] + '>' for p in nd: if self.inside_a: self.anthor_text += p htmllib.HTMLParser.feed(self, p) def start_a(self, attrs): htmllib.HTMLParser.start_a(self, attrs) self.inside_a = True for name, value in attrs: if name == 'href': self.lastlink = value def end_a(self): htmllib.HTMLParser.end_a(self) self.inside_a = False atext = re.sub('<[^>]*>', '', self.anthor_text) atext = atext.replace('&gt;', '>').replace('&lt;', '<') if atext: self.links.append((atext, self.lastlink)) self.anthor_text = '' h = MyHTMLParser() h.feed(hstr) h.close() print h.links h = LinkParser(formatter.NullFormatter()) h.feed(hstr) h.close() print h.links for r in re.finditer('<a[^>]*href="([^"]+)[^>]*>([^<]+)</a>', \ re.sub('<[^a/][^>]*>|</[^>]*[^a]>', '', hstr)): print r.group(2), '->', r.group(1) print re.search('<title>([^<]*)</title>', hstr).group(1)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 21 05:19:15 CST 2011 import optparse, sys parser = optparse.OptionParser(usage="%prog [options] [args]") parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='make lots of noise') options, args = parser.parse_args() infile = len(args)>0 and args[0] or "../data/test.xml" ######### Test xml.sax ################ from xml.sax.handler import ContentHandler from xml.sax import make_parser, SAXException class SAXHandler(ContentHandler): def __init__(self, name): print "name =",name self.display = False def startElement(self, name, attrs): print "start tag = ", name, attrs if name == "tag1": self.display = True def endElement(self, name): print "end tag = ", name if name == "tag1": self.display = False def characters(self, chars): if self.display: print "chars = '%s'"%chars def test_sax(inputfile): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name h = SAXHandler("SHandler") parser = make_parser() parser.setContentHandler(h) try: parser.parse(open(inputfile)) except SAXException, e: print e test_sax(infile) test_sax("../data/error.xml") ######### Test xml.dom ################ from xml.dom import minidom import xml.dom.minidom as mxml def test_minidom_read(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name try: doc = minidom.parse(infile) tags = doc.getElementsByTagName("tag1") for tag in tags: print tag.toxml() except Exception, e: print e test_minidom_read() def AddToNode(node, data): d = mxml.Document() type = data.__class__.__name__ if type == 'dict': for k, v in data.items(): c = d.createElement(str(k)) AddToNode(c, v) node.appendChild(c) else: node.appendChild(d.createTextNode(str(data))) def test_minidom_gen(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name d = mxml.Document() a={'name':'kevin', 'score':[('eng',99),('math',33),('cs',55)], 'room':1220} AddToNode(d.appendChild(d.createElement('root')), a) print d.toprettyxml() test_minidom_gen() test_news_xml=""" <NEWS> <DOC> <DOCNO> NYT19990101.0001 </DOCNO> <DOCTYPE> NEWS STORY </DOCTYPE> <DATE_TIME> 1999-01-01 00:01 </DATE_TIME> <HEADER> </HEADER> <BODY> <SLUG> BC-MONEY-SAVING-LADN </SLUG> <HEADLINE> TWENTY SIMPLE STEPS TOWARD PERSONAL UDGET SURPLUS </HEADLINE> (For use by NYTimes News Service clients) By DEBORAH ADAMSON c.1999 Los Angeles Daily News <TEXT> <P> LOS ANGELES -- Every year, millions of Americans pledge to put their financial house in order. This year, they say to themselves, it will be different. </P> <P> They'll save and invest more. They'll even stick to a budget. </P> <P> Indeed, the second-most popular New Year's resolution is to achieve financial goals, according to Citibank. The first? Lose weight and live more healthfully. </P> <P> XXX </P> </TEXT> </BODY> <TRAILER> </TRAILER> </DOC> <DOC> <DOCNO> NYT19990101.0002 </DOCNO> <DOCTYPE> NEWS STORY </DOCTYPE> <DATE_TIME> 1999-01-01 00:11 </DATE_TIME> <BODY> <TEXT> <P> hello </P> </TEXT> </BODY> </DOC> </NEWS> """ def test_minidom_news(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name try: recordDelim = "###" dom = minidom.parseString(test_news_xml) for doc in dom.getElementsByTagName("DOC"): docno_xml = doc.getElementsByTagName("DOCNO")[0] docno = docno_xml.childNodes[0].data.strip() print "id=%s"%(docno) print "time=%s"%(docno[:8]) body = doc.getElementsByTagName("BODY")[0] if doc.getElementsByTagName("HEADLINE") != []: headline_xml = doc.getElementsByTagName("HEADLINE")[0] title = headline_xml.childNodes[0].data.strip() else: title = docno print "title=%s"%(title) print "body=", textxml = body.getElementsByTagName("TEXT")[0] for para_xml in textxml.getElementsByTagName("P"): print para_xml.childNodes[0].data.strip() print recordDelim dom.unlink() except Exception, e: print e test_minidom_news()
Python
#!/usr/bin/env python import Tkinter top = Tkinter.Tk() label = Tkinter.Label(top, text='Hello World!') label.pack() Tkinter.mainloop()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 08 19:31:50 CST 2009 import sys, os def test_dbhash(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import dbhash, whichdb fdb='dbhash.tmp' db = dbhash.open(fdb, 'c') for i in range(9): db[str(i)] = str(i*i) for i in range(9): print i, db[str(i)] print db.keys() print db.first() print db.next() print db.next() print db.next() print db.last() db.set_location('2') print db.previous() db.close() print 'whichdb:', whichdb.whichdb(fdb) os.remove(fdb) #test_dbhash() def test_bsddb_hash(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import bsddb, whichdb fdb='bsddb_hash.tmp' db = bsddb.hashopen(fdb, 'c') for i in range(9): db[str(i)] = str(i*i) for i in range(9): print i, db[str(i)] print db.keys() print db.first() print db.next() print db.next() print db.next() print db.last() db.set_location('2') print db.previous() #db.set_location('22') db.close() print 'whichdb:', whichdb.whichdb(fdb) os.remove(fdb) #test_bsddb_hash() def test_bsddb_bt(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import bsddb, whichdb fdb='bsddb_bt.tmp' db = bsddb.btopen(fdb, 'c') for i in range(9): db[str(i)] = str(i*i) for i in range(9): print i, db[str(i)] print db.keys() print db.first() print db.next() print db.next() print db.next() print db.last() print db.set_location('2') print db.previous() print db.set_location('22') print db.next() db.close() print 'whichdb:', whichdb.whichdb(fdb) os.remove(fdb) #test_bsddb_bt() def test_bsddb_rn(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import bsddb, whichdb fdb='bsddb_rn.tmp' db = bsddb.rnopen(fdb, 'c') for i in range(1,9): db[i] = str(i*i) #for i in range(9): print i, db[str(i)] print db.keys() print db.first() print db.next() print db.next() print db.next() print db.last() print db.set_location(2) print db.previous() #print db.set_location(22) print db.next() db.close() print 'whichdb:', whichdb.whichdb(fdb) os.remove(fdb) #test_bsddb_rn() def test_gdbm(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import gdbm, whichdb fdb='gdbm.tmp' db = gdbm.open(fdb, 'c') for i in range(9): db[str(i)] = str(i*i) db.close() db = gdbm.open(fdb) k = db.firstkey() while k != None: print k k = db.nextkey(k) db.close() print 'whichdb:', whichdb.whichdb(fdb) os.remove(fdb) #test_gdbm() def test_anydbm(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import anydbm, whichdb fdb='anydbm.tmp' db = anydbm.open(fdb, 'c') for i in range(9): db[str(i)] = str(i*i) #print db.keys(), db.values() db.close() db = anydbm.open(fdb, 'w') del db['3'] for k, v in db.iteritems(): print k, v #k = db.firstkey() #while k != None: #print k #k = db.nextkey(k) db.close() print 'whichdb:', whichdb.whichdb(fdb) os.remove(fdb) #test_anydbm() def test_sqlite(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import sqlite, random fdb = 'sqlite.tmp' conn = sqlite.connect(fdb) c = conn.cursor() c.execute('''create table stocks (id integer, price real)''') for i in range(10): c.execute('insert into stocks values (%d, %f)', (i,random.random())) conn.commit() c.execute('select * from stocks order by price') for row in c: print row c.close() os.remove(fdb) #test_sqlite() def tgdbm(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name import gdbm, random fdb = 'tgdbm.tmp' db = gdbm.open(fdb, 'c') len = 0 for i in range(999): n = random.randint(999, 99999) db[str(i)] = 'a' * n len += n db.close() #os.remove(fdb) #db = gdbm.open(fdb, 'w') #db.reorgnize() #db.close() print len, os.path.getsize(fdb) tgdbm()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 28 03:22:43 PM CST 2008 import ftplib ftp = ftplib.FTP('127.0.0.1') ftp.login() #ftp.login('ftp') #ftp.login('fankai') print ftp.retrlines('LIST') ftp.retrbinary('RETR CHANGES.txt', open('txt', 'wb').write) #print ftp.getwelcome() #print ftp.retrlines('RETR CHANGES.txt') #print ftp.sendcmd('LIST') #ftp.storlines('STOR incoming/txt2', open('txt')) #ftp.storbinary('STOR incoming/txt3', open('txt')) print ftp.retrlines('LIST incoming') print ftp.nlst() print ftp.nlst('incoming') print ftp.dir() print ftp.cwd('incoming') print ftp.dir() print ftp.pwd() ftp.cwd('..') print ftp.size('CHANGES.txt') print ftp.dir('CHANGES.txt') #print ftp.size('incoming') ftp.quit()
Python
#!/usr/bin/env python import sys g = 9 def ff(): """function ff. Test basic function The first function""" a = 1 print 'file:', sys._getframe().f_code.co_filename print 'func:', sys._getframe().f_code.co_name print 'stacksize:', sys._getframe().f_code.co_stacksize print 'consts:', sys._getframe().f_code.co_consts print 'argcount:', sys._getframe().f_code.co_argcount print 'varnames:', sys._getframe().f_code.co_varnames print 'first lineno:', sys._getframe().f_code.co_firstlineno print 'line:', sys._getframe().f_lineno print 'lasti:', sys._getframe().f_lasti print 'locals:', sys._getframe().f_locals print 'globals:', sys._getframe().f_globals print 'f_exc_type:', sys._getframe().f_exc_type print 'f_exc_traceback:', sys._getframe().f_exc_traceback b = '' print 'locals:', sys._getframe().f_locals print 'trace:', sys._getframe().f_trace return "a first function" print ff() print ff.__doc__ print ff.__name__ def test_param(a, b=4, c=5): print a, b, c test_param(4,3,5) test_param(c=3, a=6) print map(lambda x:x *2, [4]) print reduce(lambda x, y: x + y, [1, 2, 3], 4) print filter(lambda x:x > 3, [5, 6, 4, 2, 7]) def function(a, b): print a, b apply(function, ("crunchy", "frog")) apply(function, (), {"b": "frog", "a": "crunchy"}) apply(function, (), {"a": "crunchy", "b": "frog"}) def counter(start_at=0): count = [start_at] def incr(): count[0] += 1 return count[0] return incr print counter(4) c = counter(5) d = counter(66) print c() print c() print d() print c() def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [method for method in dir(object) if callable(getattr(object, method))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) #print info(info) #print callable(info) def test_generator(): print sum(1 for i in range(1000) for j in range(1000)) for item in gen(): print item def gen(): yield 1 yield 2 #test_generator()
Python
#!/usr/bin/env python import time, os, timeit try: f = open("data/test.txt", "rb") except IOError: print "data/test.txt not exist." else: print f.name print f.readlines() print f.tell() f.seek(0, 0); print f.read(4) print f.read() finally: f.close() ts = time.clock() f = open('data/test.dat', 'w') for i in range(1000000): f.write('abcdefg') print "Write %d bytes cost %f seconds" % (f.tell(), time.clock() - ts) f.close() ts = time.clock() f = open('data/test.dat', 'rb') s = f.read() print "Read %d bytes cost %f seconds" % (f.tell(), time.clock() - ts) f.close() ts = time.clock() f = open('data/test2.dat', 'w') f.write(s) print "Write %d bytes cost %f seconds" % (f.tell(), time.clock() - ts) f.close()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 28 18:29:49 CST 2008 import timeit, sys def f0(): pass def f1(a): pass def f2(*a): pass def time_random(): print timeit.Timer('random.random()', 'import random').timeit() print timeit.Timer('random.uniform(1,10)', 'import random').timeit() print timeit.Timer('random.randint(1,100)', 'import random').timeit() print timeit.Timer('random.randint(1,100000000)', 'import random').timeit() print timeit.Timer('random.randrange(0,101,2)', 'import random').timeit() print timeit.Timer('random.choice("abcdefg")', 'import random').timeit() print timeit.Timer('random.sample("abcdefg", 2)', 'import random').timeit() def time_misc(): print timeit.Timer('pass').timeit() print timeit.Timer('a=1').timeit() print timeit.Timer('b=None').timeit() print timeit.Timer('s="abcedfg"').timeit() print timeit.Timer('a=(1,2,3,4)').timeit() print timeit.Timer('a=[1,2,3,4]').timeit() print timeit.Timer('a={1:2,3:4}').timeit() print timeit.Timer('a=[8]*100').timeit() print timeit.Timer('a=1+2').timeit() print timeit.Timer('1+2').timeit() print timeit.Timer('1+2+3').timeit() print timeit.Timer('.1+.2+.3').timeit() print timeit.Timer('222*333').timeit() print timeit.Timer('22**33').timeit() print timeit.Timer('123450/333').timeit() print timeit.Timer('123450.0/333').timeit() print timeit.Timer('123450.0/333').timeit() print timeit.Timer('"*"*9').timeit() print timeit.Timer('str(123)').timeit() print timeit.Timer('int("123")').timeit() print timeit.Timer('float("123.45")').timeit() def time_io(): #print timeit.Timer('print 0,').timeit(10000) #print timeit.Timer('print 0').timeit(10000) if not os.path.exists('tmp'): os.mknod('tmp') print timeit.Timer('open("tmp")').timeit(10000) print timeit.Timer('open("tmp", "a")').timeit(10000) os.remove('tmp') print timeit.Timer('os.mknod("tmp")\nos.remove("tmp")', 'import os').timeit(10000) print timeit.Timer('os.mknod("tmp")\nos.rename("tmp", "tmp2")\nos.remove("tmp2")', 'import os').timeit(10000) print timeit.Timer('open("tmp","a").write(" "*10)', 'import os').timeit(10000) print timeit.Timer('open("tmp","a").write(" "*1000)', 'import os').timeit(10000) print timeit.Timer('open("tmp","w").write(" "*1000)', 'import os').timeit(10000) print timeit.Timer('open("tmp","a").write(" "*10000)', 'import os').timeit(10000) print timeit.Timer('open("tmp","w").write(" "*10000)', 'import os').timeit(10000) print timeit.Timer('open("tmp","a").write(" ")', 'import os').timeit(10000) print timeit.Timer('f=open("tmp")\nf.seek(12345)', 'import os').timeit(10000) os.remove('tmp') def time_func(): timeit.f0=f0 timeit.f1=f1 timeit.f2=f2 timeit.arg=99 print timeit.Timer('f0()').timeit() print timeit.Timer('f1(arg)').timeit() print timeit.Timer('f2(arg,arg,arg)').timeit() print timeit.Timer('f2([arg]*100)').timeit() sys.stdout=sys.stderr time_func() #time_io() #time_misc() #time_random()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 26 06:35:16 CST 2008 import sys, readline, atexit, os def save_history(histfile): readline.write_history_file(histfile) class MyCompleter: def __init__(self): self.words = "perl", "pyjamas", "python", "pythagoras" self.prefix = None def complete(self, prefix, index): print prefix, index if prefix != self.prefix: # we have a new prefix! # find all words that start with this prefix self.matching_words = [ w for w in self.words if w.startswith(prefix) ] self.prefix = prefix try: return self.matching_words[index] except IndexError: return None def test_readline(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name words = "perl", "pyjamas", "python", "pythagoras" histfile = os.path.expanduser('~/.bash_history') readline.read_history_file(histfile) atexit.register(readline.write_history_file, histfile) readline.parse_and_bind("tab: complete") readline.set_completer(MyCompleter().complete) for i in range(3): print(raw_input('$')) test_readline()
Python
#!/usr/bin/env python import sys, getopt, random from socket import * PORT = 12345 def udp_server(): s = socket(AF_INET, SOCK_DGRAM) s.bind(('', PORT)) while True: print 'Received "%s" from %s.' % s.recvfrom(1024) s.close() def udp_client(str): s = socket(AF_INET, SOCK_DGRAM) HOST = 'localhost' ADDR = (HOST, PORT) s.sendto(str, ADDR) while True: line = raw_input() if not line: break s.sendto(line, ADDR) print 'Sent ' + str s.close() def tcp_server(): myHost = '' sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, PORT)) sockobj.listen(5) while True: connection, address = sockobj.accept() print 'Server connected by', address while True: data = connection.recv(1024) if not data: break connection.send('Echo=>' + data) connection.close() def tcp_client(): serverHost = 'localhost' # server name, or: 'starship.python.net' message = ['Hello network world\n'] # default text to send to server sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, PORT)) print sockobj.getsockname() while True: line = raw_input() print sockobj.send(line) data = sockobj.recv(1024) print 'Client received:', `data` sockobj.close() # close try: opts, args = getopt.getopt(sys.argv[1:], 'csud') except getopt.GetoptError, e: print e sys.exit(1) if len(opts) > 0: opt = opts[0][0] if opt == '-c': print 'Start tcp client ...' tcp_client() elif opt == '-s': print 'Start tcp server ...' tcp_server() elif opt == '-u': print 'Start udp server ...' udp_server() else: print 'Start udp client ...' udp_client(' '.join(sys.argv))
Python
#!/usr/bin/env python print "Hello, world!" import sys, os import glob print '***Test Sys Module***' print "path =", sys.path print "platform =", sys.platform print "maxint =", sys.maxint print "version =", sys.version print '***Test OS Module***' if (sys.platform == "win"): print os.getpid() print os.getcwd() print os.listdir("c:\\") print os.abort.__module__ print os.path.dirname("d:\\") print os.path.split("d:\\test.txt") print os.path.splitext("test.txt") print [f for f in os.listdir("d:\\") if os.path.isfile(os.path.join('d:\\', f))] print (os.pardir, os.curdir,os.sep, os.pathsep, os.linesep) print os.listdir(r'c:/') print os.path.getsize(r'c:\boot.ini') print os.path.abspath('.') os.system('dir') print os.popen('dir ..').read() print os.environ os.environ['user'] = 'fk' print os.environ['user'] print glob.glob(r"d:\*\*txt")
Python
#!/usr/bin/env python # @author FAN Kai, Peking University # @date Dec 23 04:14:34 PM CST 2008 import threading, time, sys, os, random def disp(): print 'Current:', threading.currentThread() print 'pid = ', os.getpid() print 'ppid = ', os.getppid() print 'uid = ', os.getuid() print 'gid = ', os.getgid() def info(): print 'Thread count:', threading.activeCount() print 'mt count=%d create=%d calc=%d sleep=%d' % ( mt.count, mt.create, mt.calc, mt.sleep) #print 'All:', threading.enumerate() class mt(threading.Thread): def run(self): glock.acquire() t = threading.currentThread() print 'Thread %s begins.' % t.getName() mt.count += 1 mt.create += 1 info() glock.release() #t.setName('abc thread') if random.random() < 0.5: mt.calc += 1 for i in range(3000000): random.random() ** 2 mt.calc -= 1 else: mt.sleep += 1 time.sleep(3) mt.sleep -= 1 glock.acquire() print 'Thread %s ends.' % t.getName() mt.count -= 1 info() glock.release() sema.release() sys.stdout = sys.stderr glock = threading.Lock() sema = threading.Semaphore(3) threads = [] mt.count = 0 mt.create = 0 mt.calc = 0 mt.sleep = 0 #print 'thread stack size = %d', threading.stack_size() #print 'thread stack size = %d', threading.stack_size() for i in range(900): sema.acquire() t = mt() t.setDaemon(True) threads.append(t) t.start() for t in threads: t.join()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@pku.edu.cn), Peking University # @date Dec 25 09:15:15 CST 2008 import sys, collections, heapq, array def test_dict(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name d = {"user":"fk", "key":"joke", 6:9.9} print d, d["user"], d["key"], d[6] print d.items(), d.keys(), d.values() print d.has_key("fk"), d.has_key("user"), d.get("user") print d.__class__ d["user"] = "fankai" d["lab"] = "cnds" print d def test_list(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name li = ["a", 9, "fuck", 8.7] print li, li[1], li[-1] print li[0:-1], li[2:len(li)], li[:1] li.append("world") print li[3:] li.insert(1, "the") print li[:3] li.extend(['o', 'p', 'q']) print li li.append(['r', 's', 't']) print li print li.index('a'), 'b' in li while len(li) > 5:print li.pop() print li li.remove(9) print "List after remove 9:",li li += [1, 2] * 2 + [5, 6] print li print [elem*2 for elem in li] li.sort() print li print [(x, y) for x in range(3) for y in range(3)] def test_tuple(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name t = ('t', 'u', 5, 'e') print t, t[2:], t[-1] print tuple(li) def test_misc(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name print "%s=%s" % ('a', 'b') print "%d > %s" % (9, '8') print "%+.2f" % 1.5 print ';'.join(['1', '2', '3']) print '2, 4, 5'.split(',', 1) print "a".ljust(5), "b" print 'a' and 1 print '-'*48, '\nFunc:', sys._getframe().f_code.co_name print type(1), type('a'), type(()), type([]), type({}) print dir(()) print dir([]) print dir({}) print dir.__doc__ print ().__doc__ print 5<3 and 'yes' or 'no' print 1 in (1, 2) print 1 in {1:2} print 2 in [1, 2] def test_deque(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name dq = collections.deque([1,2,3]) print dq dq.append(56) dq.appendleft(88) dq.extend([-1,-2]) print dq print dq.pop() print dq.pop() print dq.popleft() print dq dq.rotate(3) print dq def test_heapq(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name h = [9,8,3,4,2,7] print heapq.nlargest(3, h) print heapq.nsmallest(3, h) print h heapq.heapify(h) print h heapq.heappush(h, -2) print h print heapq.heappop(h) print h print heapq.heapreplace(h, 99) print h def test_array(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name a = array.array('i') a.append(4) a.append(0) a.append(-1) print a print a.itemsize print a.itemsize print a.buffer_info() print a.count(3) print a.count(4) print array.array('c', 'hello world') print array.array('d', [1.0, 3, -9]) def test_queue(): import Queue q = Queue.Queue() print q.qsize() q.put(1) print q.get() try: print q.get(False) except Queue.Empty, e: print 'empty' #print q.task_done() #q.join() test_queue() #test_tuple() #test_misc() #test_list() #test_deque() #test_heapq() #test_array() from bisect import * def test_bisect(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name a = [1,3,5,5,7,9] print bisect_left(a, 4) print bisect_left(a, 5) print bisect_right(a, 5) print bisect(a, 5) insort(a, 4) print a test_bisect()
Python
#!/usr/bin/env python # @author FAN Kai, Peking University # @date Dec 16 21:18:52 CST 2008 import scipy.linalg from scipy import array, matrix import time, random n = 4 a = array([random.randint(0, n*n) for e in range(n*n)]) a.resize(n,n) m = matrix(a) #print a*a #print time.clock() im = scipy.linalg.inv(m) aa = matrix([1,2,3,4]).T s = scipy.linalg.solve(m,aa) print m print s print m*s print scipy.linalg.norm(m) print scipy.linalg.eig(m)
Python
#!/usr/bin/env python # @author FAN Kai, Peking University # @date Dec 12 19:55:18 CST 2008 # Test data persistance import shelve,pickle, os import zlib, gzip, zipfile, tarfile import ConfigParser, time import csv, sys, random, timeit file1 = 'test_pickle.dat' file2 = 'test_shelve.dat' file3 = 'test_dbm.dat' data = {} data['a'] = 'joke' data['b'] = range(1,7) def test_pickle(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name str = pickle.dumps(data) str0 = pickle.dumps(data, 0) str1 = pickle.dumps(data, 1) str2 = pickle.dumps(data, 2) strh = pickle.dumps(data, pickle.HIGHEST_PROTOCOL) print len(str), len(str0), len(str1), len(str2), len(strh) print 'loaded data from string:', pickle.loads(str) pickle.dump(data, open(file1, 'wb')) print 'loaded data from file:', pickle.load(open(file1, 'rb')) def test_shelve(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name d = shelve.open(file2, writeback=True) for k in data.keys(): d[k] = data[k] print d d['b'].append(0) print d d.close() print 'loaded data:', shelve.open(file2) def ts_aux(count): print 'insert %d items' % count timeit.ds = shelve.open(timeit.f) #print timeit.Timer('k=str(random.random())\nks.append(k)\nds[k]=" "*1000\nds.sync()', 'import random').timeit(count) print timeit.Timer('k=str(random.random())\nks.append(k)\nds[k]=" "*1000', 'import random').timeit(count) print timeit.Timer('ds.sync()').timeit(1) print timeit.Timer('len(ds)').timeit(10000) print timeit.Timer('str(random.random()) in ds', 'import random').timeit(10000) print timeit.Timer('ks[random.randint(0,len(ks)-1)] in ds', 'import random').timeit(10000) timeit.ds = shelve.open(timeit.f) print timeit.Timer('ds[ks[random.randint(0,len(ks)-1)]]', 'import random').timeit(10000) timeit.ds.close() print 'db count=%d size=%d' % (len(timeit.ks), os.path.getsize(timeit.f)) def time_shelve(): timeit.f = 'time_shelve.dat' if os.path.exists(timeit.f): os.remove(timeit.f) timeit.ks = [] print timeit.Timer('str(random.random())', 'import random').timeit(10000) print timeit.Timer('ks.append(str(random.random()))', 'import random').timeit(10000) print timeit.Timer('len(ks)', 'import random').timeit(10000) print timeit.Timer('random.randint(0,len(ks))', 'import random').timeit(10000) print timeit.Timer('ks[random.randint(0,len(ks)-1)]', 'import random').timeit(10000) print timeit.Timer('d=shelve.open(f)\nd.close()', 'import shelve').timeit(100) timeit.ks=[] ts_aux(10000) ts_aux(10000) ts_aux(10000) ts_aux(10000) #os.remove(timeit.f) sys.stdout=sys.stderr time_shelve() def test_zlib(): str = ' '.join(map(chr, range(65, 123)))*88 print 'len:', len(str) for i in range(0, 10): cs = zlib.compress(str, i) print 'compress level', i, len(cs) def test_gzip(): print '\nTesting gzip ...' gzip.open('test.gz', 'wb').write(str) assert str == gzip.open('test.gz').read() def test_tarfile(): print '\nTesting tarfile ...' tf = tarfile.open('test.tar', 'w') tf.add(file1, 'tmp') tf.add(file2) print tf.getnames() #tf.extract('d/dattest.txt') tf.close() print 'test.gz is tarfile? ', tarfile.is_tarfile('test.gz') print 'test.tar is tarfile? ', tarfile.is_tarfile('test.tar') print '\nTesting zipfile ...' zf = zipfile.ZipFile('test.zip', 'w', zipfile.ZIP_DEFLATED) zf.write('test.tar') #print zf.namelist() print zf.getinfo('test.tar').compress_size, zf.getinfo('test.tar').file_size zf.close() def test_csv(): w = csv.writer(open("test.csv", "wb")) w.writerow([1,'b',2,'c',3]) w.writerow([2,'b',2,'c',3]) del w r = csv.reader(open("test.csv", "rb")) try: while True: print r.next() except:pass del r print '...' for row in csv.reader(open("test.csv", "rb")): print row def test_configparser(): try: conf = ConfigParser.ConfigParser() conf.read('data/test.ini') print conf.has_section('lab') print conf.options('lab') for sec in conf.sections(): print sec, conf.items(sec) print conf.getint('lab', 'room') conf.set('lab', 'room', '1117') conf.write(open('data/test2.ini', 'wb')) except Exception, e: print e def clean(): os.remove(file1) os.remove(file2) os.remove(file3) os.remove('test.gz') os.remove('test.tar') os.remove('test.zip') os.remove('test.csv')
Python
#!/usr/bin/env python # @author FAN Kai (fankai@pku.edu.cn), Peking University # @date Dec 25 08:49:51 CST 2008 import datetime dd = datetime.timedelta(1,1,1) de = datetime.timedelta(0,6,9) print dd.min print dd.max print dd.resolution print dd+de print td = datetime.date.today() print td print td.min print td.max print td.toordinal() print td.weekday() print td.isocalendar() print td.ctime() print dt = datetime.datetime(td.year, td.month, td.day) print dt print dt.today() print dt.now() print dt.utcnow() print dt.tzinfo print tz = datetime.tzinfo() print tz print t = datetime.time() print t print t.isoformat() print t.utcoffset() print t.dst()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 26 06:32:09 CST 2008 import sys, os, time def test_fork(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name pid = os.fork() if pid == 0: print 'child', os.getpid() for i in xrange(3, 0, -1): print 'child exits in %d seconds'%i time.sleep(1) print 'child exits.' sys.exit(12) else: print 'parent', os.getpid() for i in xrange(3, 0, -1): print 'parent exits in %d seconds'%i time.sleep(1) #print 'kill', pid #os.kill(pid, signal.SIGKILL) #print os.wait() print 'parent exits.' sys.exit(0) def test_spawn(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name args = ['a0', 'a1', 'a2'] print os.spawnlp(os.P_NOWAIT, 'echo', 'echo', 'a', 'b') while True: pass def test_exec(): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name args = ['a0', 'a1', 'a2'] #os.execl('/home/kevin/test', 'joke', 'hello') #os.execv('/home/kevin/test', args) #os.execv('/home/kevin/py.py', args) os.execlp('echo', 'echo', 'a', 'b') sys.stdout=sys.stderr #test_exec() #test_spawn() test_fork()
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 03 07:14:53 CST 2009 import cgi, cgitb, Cookie, os cgitb.enable() if os.environ.has_key('HTTP_COOKIE'): cstr = os.environ['HTTP_COOKIE'] else: cstr = '' cookie = Cookie.SimpleCookie(cstr) if 'count' in cookie: cookie['count'] = int(cookie['count'].value) + 1 else: cookie['count'] = 0 cookie['count']['max-age'] = 60*60*24 print cookie print '''Content-Type: text/html''' print print'''<html> <title>Test CGI</title> <body> <h1>CGI in Python</h1> fuck the world<br> ''' print 'found %d cookies' %len(cookie.keys()) print '<ul>' for k in cookie.keys(): m = cookie[k] print '<li>%s: %s' % (k, m.value) print '</ul><p>' form = cgi.FieldStorage() #print form.keys() cgi.print_environ() print '</body></html>'
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 29 09:31:11 PM CST 2008 from numpy import * a = array(xrange(1,9), int) b = a.astype('float') print a.shape print a.dtype print a+a print a*a print a/a print a/3 print b/3 c = arange(6, dtype='float') print c d = c * pi / len(c) print d print d[0:6:2] t = array([False,True,False,True,True], bool) print d[t] dt = sort(abs(d-1.5)) print dt print abs(d-1.5) <= dt[3] e = d[abs(d-1.5) <= dt[3]] print e a = array([[0,1,2],[3,4,5],[6,7,8]]) b=a[1:3,0:2] print b bc = b.copy() a[1:3,0:2] = 2 print b print bc print dot(b, bc) print b * bc x,y = mgrid[0:5:1, 0:10:2] print x print y print x + y print (x+y)**2 a = zeros((2,2), dtype=int) print a print ones((3,4), dtype=float) a = array([[0,1],[2,3]]) print a.repeat(2, axis=0) print a.repeat(3, axis=1) print a.repeat(2, axis=None)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Dec 27 17:48:52 CST 2008 from pylab import * subplot(221) plot([0.5,1,2,3], [0.25,1,4,9]) t = arange(0,5,.2) plot(t,t,'r--',t,t**2,'bs') axis([0,4,0,20]) subplot(222) plot([4,5,6]) subplot(223) t = arange(0,3,.1) plot(t,t,'r--',t,t**2,'bs',t,t**3) xlabel('xxx') ylabel('yyy') title(r'Expo') text(1.2,5,r'$y=x^3$') annotate(r'$y=x^2$', xy=(2,4), xytext=(2.5,4.1), arrowprops=dict(facecolor='black', shrink=0.01),) grid(True) axis([0,3,0,10]) subplot(224) title('TEXT') text(1,1,r'fuck the world', horizontalalignment='center', verticalalignment='center', fontsize = 22, bbox={'facecolor':'red','alpha':0.5}) axis([0,2,0,2]) show() #savefig('a.png')
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Apr 24 14:59:56 CST 2009 import random def average_sim(sim, item, group): if not group: return 1 return sum([sim[item][x] for x in group])/float(len(group)) def kmeans(sim, group_count): num = len(sim) seeds = random.sample(range(0, num), group_count) groups = [[seeds[i]] for i in range(group_count)] for round in range(0, 10): print groups gsim = [[average_sim(sim, i, g) for g in groups] for i in range(num)] #for row in gsim: print row new_groups = [[] for g in range(group_count)] for i in range(num): mg = max(zip(gsim[i], range(group_count)))[1] new_groups[mg].append(i) if new_groups == groups: break groups = new_groups sim = [[1]*9 for i in range(9)] for i in range(1, 9): for j in range(0, i): sim[i][j] = sim[j][i] = random.random() #print sim kmeans(sim, 5)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 23 05:29:50 PM CST 2009 import networkx as nx def draw(g): import matplotlib.pyplot as plt #nx.draw(g) #nx.draw_random(g) nx.draw_circular(g) #nx.draw_spectral(g) plt.show() def gen(): petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() k5 = nx.complete_graph(5) k35 = nx.complete_bipartite_graph(3,5) draw(k35) def basic(): g = nx.Graph() g.add_node(9) g.add_nodes_from(range(5)) #g.add_node('n') #g.add_node('m') g.add_edge(2,3) g.add_edge(1,3) g.add_edge(1,4) g.add_edge('n', 'm', 'red') g.remove_node(0) print g.nodes() print g.edges() print g.edges(data=True) print g.edges(2,3) print g.edges(2,1) print nx.connected_components(g) print nx.degree(g) print g.degree(with_labels=True) print nx.clustering(g) print g.size(), g.number_of_edges() g.remove_node('n') g.remove_node('m') #mst = kruskal_mst(g) basic() gen()
Python
#!/usr/bin/env python import sys, os sys.stdout=sys.stderr def lcs(a, b): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name nr = len(a) + 1 nc = len(b) + 1 c = [[0]*nc for i in range(nr)] s = [['*']*nc for i in range(nr)] for i in range(1, nr): for j in range(1, nc): if a[i-1] == b[j-1]: c[i][j] = c[i-1][j-1] + 1 s[i][j] = '\\' else: el = c[i][j-1] eu = c[i-1][j] c[i][j] = el > eu and el or eu s[i][j] = el > eu and '-' or '|' for r in c: print r for r in s: print ' '.join(r) r = '' i = nr - 1 j = nc - 1 while i >=1 or j >=1: if s[i][j] == '\\': r = a[i-1] + r i -= 1 j -= 1 elif s[i][j] == '-': j -= 1 else: i -= 1 print 'lcs=', r #lcs('aasdfuh;sadjfalskdjfc', 'acasdfhoaei;asdijfasduifha;sdifjf') def qsort(dat): if dat == []: return [] a = [e for e in dat[1:] if e < dat[0]] b = [e for e in dat[1:] if e >= dat[0]] print a, b return qsort(a) + dat[0:1] + qsort(b) print qsort([3,2,1])
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Apr 22 21:07:32 CST 2009 import re, sys def html2text(page): page = re.sub('<script[^<]*</script>', '', page) page_text = re.sub('<[^>]*>|&[^;]*;', '', page) return page_text
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 05 19:40:49 CST 2009 import math def entropy(d): e = 0 for p in d: e -= p*math.log(p, 2) return e print entropy([0.5, 0.5]) print entropy([0.2, 0.8]) print entropy([0.25,0.25, 0.25, 0.25]) print entropy([0.25] * 4) print entropy([0.05] * 20) a=[(1,2), (3,4)] b=[(1,3), (4,5)] def cos(a, b): s = 0 for i in range(len(a)): s += a[i]*b[i] aa = math.sqrt(sum(i*i for i in a)) bb = math.sqrt(sum(i*i for i in b)) return s / aa / bb print cos((-1,0), (-1, 1)) print cos((-2,0), (-2, 2))
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Oct 01 17:50:09 CST 2010 cnta = 4 cntb = 5 edges = [[0, 0], [0,1], [1,0]] lines = [0, 0] def find_edge(point, ex): for edge in edges: if edge[0] == point and edge[1] not in includedb: return edge[1] return None def find_edge2(point, ex): for edge in edges: if edge[1] == point and edge[0] not in includeda: return edge[0] return None def find_lines(): for edge in edges: if edge[0] not in includeda and edge[1] not in includedb: includeda.append(edge[0]) includedb.append(edge[1]) return edge return None def find(lines): if lines[0] != -1: a = find_edge(lines[0], lines[1]) b = find_edge2(lines[-1], lines[-2]) if a == None or b == None: return None includedb.append(a) includeda.append(b) lines = [-1, a]+lines+[b] else: a = find_edge2(lines[1], lines[2]) b = find_edge(lines[-1], lines[-2]) if a == None or b == None: return None includeda.append(b) includedb.append(a) lines = [a]+lines[1:]+[b] return lines includeda = [] includedb = [] while True: lines = find_lines() if lines == None: break print lines, includeda, includedb while lines != None: lines = find(lines) print lines, includeda, includedb
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 16 04:02:42 PM CST 2009 import os, time, cPickle class fdb: def __init__(self, path): if os.path.exists(path): f = open(path, 'rb+') pos = int(f.read(8), 16) f.seek(pos) idxstr = f.read() self.idx = cPickle.loads(idxstr) #print self.idx self.pos = pos self.dat = f else: self.idx = {} self.pos = 8 os.mknod(path) self.dat = open(path, 'rb+') self.closed = False def __del__(self): pass #if not self.closed: #self.close() def keys(self): return self.idx.keys() def put(self, key, value): #print self.pos self.dat.seek(self.pos) self.idx[key] = (self.dat.tell(), len(value)) self.dat.write(value) self.pos = self.dat.tell() def get(self, key): if key in self.idx: pos, len = self.idx[key] self.dat.seek(pos) return self.dat.read(len) def close(self): self.dat.seek(0) self.dat.write('%08x'%self.pos) idxstr = cPickle.dumps(self.idx) self.dat.seek(self.pos) #print self.pos self.dat.write(idxstr) #self.dat.truncate() self.dat.close() self.closed = True if __name__ == "__main__": import sys #os.system('rm fdb_tmp') db = fdb('fdb_tmp') for i in range(10): db.put(i, str(i)) db.close() db = fdb('fdb_tmp') for k in db.keys(): print k, db.get(k)
Python
from numpy import matrix from scipy import * A=matrix([[1,0,1,0,0,0],[0,1,0,0,0,0],[1,1,0,0,0,0],[1,0,0,1,1,0],[0,0,0,1,0,1]]) # svd T,s,D=linalg.svd(A) #print T #print D #print 'SIGMA :',s # simplify svd TS=T[0:,0:2] DS=D[0:2] ss=matrix([[0.0,0],[0,0]]) ss[0,0]=s[0] ss[1,1]=s[1] print 'new SIGMA Matrix :' print ss print 'Simplified Term Matrix :' print TS print 'Simplified Doc Matrix :' print DS #query q=matrix([1,0,1,1,0]) ssI=ss.I qq=q*TS*ssI print 'Query in LSI space :', qq print 'Similarity with each doc :' for i in range(0,6): v = DS.T[i] print inner(v,qq)/sqrt(inner(v,v))/sqrt(inner(qq,qq))
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 04 10:57:30 AM CST 2009 import random, sys def graph(n, m=0): h = [[m]*(i+1)+[random.randint(1,99) for j in range(i+1, n)] for i in range(n)] g = [[h[j][i]-m for j in range(i)]+[h[i][j]-m for j in range(i, n)] for i in range(n)] return g def prim(g): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name s = [0] v = range(1, len(g)) es = [] t = 0 for i in range(len(g) - 1): min = 99999 for r in v: for d in s: if g[r][d] < min: min = g[r][d] j = r e = (r, d) s.append(j) v.remove(j) es.append(e) t += min print s, v, es print es, t def kruskal(g): size = len(g) print '-'*48, '\nFunc:', sys._getframe().f_code.co_name parts = [[i] for i in range(len(g))] es = [(g[i][j], i, j) for i in range(size) for j in range(i+1,size)] es.sort() te = [] t = 0 for e in es: for part in parts: if e[1] in part: p1 = part if e[2] in part: p2 = part if p1 != p2: p = p1.extend(p2) parts.remove(p2) te.append(e) t += e[0] #print parts, te print te, t g = graph(9, 9) for r in g:print r #prim(g) kruskal(g)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 04 09:38:47 AM CST 2009 v = range(5) e = [(0,1), (0,2), (0, 3), (0, 4), (1,3), (2, 3), (2, 4), (3, 4)] size = 5 max = 0 maxr = [0]*5 def check(r, index): global max, maxr print 'check', index, r for i in range(index + 1): if r[i] == 0: continue for j in range(i + 1, index + 1): if r[j] == 0: continue if (i, j) not in e: return False m = sum(r[:index+1]) if m > max: print 'found', m, max, r max = m for i in range(index+1): maxr[i] = r[i] return True def floor(r, index): return sum(r[:index+1]) + size - index - 1 def back(n): r = [-1]*n index = 0 cnt = 0 while index >= 0: cnt += 1 print index, r r[index] += 1 if r[index] == 2: r[index] = -1 index -= 1 elif floor(r, index) > max and check(r, index): if index < n-1: index += 1 print cnt back(5) print max, maxr
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 05 17:08:28 CST 2009 import random, sys sys.stdout=sys.stderr size=18 dim=3 k=3 pts=[[random.randint(-9,9) for i in range(dim)] for j in range(size)] print pts s = [None]*3 for i in range(k): s[i] = [p for p in pts[i]] print s clast = None while True: cluster = [[] for i in range(k)] for i in range(size): p = pts[i] dmin = None for c in range(k): d = 0 for j in range(dim): d += (p[j] - s[c][j]) ** 2 if dmin is None or d < dmin: dmin = d cc = c cluster[cc].append(i) print clast, cluster if cluster == clast: break clast = [[e for e in c] for c in cluster] raw_input() for i in range(k): s[i] = [0]*dim for j in range(dim): s[i][j] = sum(pts[i][j] for i in cluster[i]) / len(cluster[i]) print s print cluster
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 04 09:38:47 AM CST 2009 v = range(5) e = [(0,1), (0,2), (0, 3), (0, 4), (1,3), (2, 3), (2, 4), (3, 4)] size = 5 max = 0 maxr = [0]*5 def check(r, index): global max, maxr print 'check', index, r for i in range(index + 1): if r[i] == 0: continue for j in range(i + 1, index + 1): if r[j] == 0: continue if (i, j) not in e: return False m = sum(r[:index+1]) if m > max: print 'found', m, max, r max = m for i in range(index+1): maxr[i] = r[i] return True def floor(r, index): return sum(r[:index+1]) + size - index - 1 def back(n): r = [-1]*n index = 0 cnt = 0 while index >= 0: cnt += 1 print index, r r[index] += 1 if r[index] == 2: r[index] = -1 index -= 1 elif floor(r, index) > max and check(r, index): if index < n-1: index += 1 print cnt back(5) print max, maxr
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 05 20:27:18 CST 2009 import random def random_shuffle(a): size = len(a) for i in range(size-1): t = a[i] s = random.randint(i+1, size-1) a[i] = a[s] a[s] = t def jc(a, b): sa = set(a) sb = set(b) r = .0 + len(sa.intersection(sb)) r /= len(sa.union(sb)) return r def shingle(a, w): size = len(a) s = set([]) for i in range(size-w+1): s.add(tuple(a[i:i+w])) return list(s) x = [1,2,3,4,5]*55 y = [1,2,3,4,5]*55 random_shuffle(x) random_shuffle(y) xx = shingle(x, 3) yy = shingle(y, 3) import md5 xm = [md5.new(str(e)).hexdigest() for e in xx] ym = [md5.new(str(e)).hexdigest() for e in yy] print len(xx) print len(yy) print jc(xx,yy) print jc(xm,ym) cnt = 0 n = 10000 for i in range(1000): size = min(len(xx), len(yy)) #pi = random.sample(range(n), n) #am = [pi[int(e, 16)%n] for e in xm] #bm = [pi[int(e, 16)%n] for e in ym] d = random.randint(1000000, 2000000) am = [int(e, 16) % d for e in xm] bm = [int(e, 16) % d for e in ym] if min(am) == min(bm): cnt += 1 print cnt
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 04 10:41:19 AM CST 2009 import random def NF(objs): cnt = 1 blank = 1 for w in objs: if w < blank: blank -= w else: cnt += 1 blank = 1 - w print cnt def FF(objs): boxs = [] for w in objs: done = False for i in range(len(boxs)): if w < boxs[i]: boxs[i] -= w done = True break if not done: boxs.append(1-w) print len(boxs) objs = [random.random() for i in range(1000)] NF(objs) FF(objs) FF(sorted(objs)) FF(sorted(objs, reverse=True))
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 04 10:57:30 AM CST 2009 import random, sys def graph(n, m=0): h = [[m]*(i+1)+[random.randint(1,99) for j in range(i+1, n)] for i in range(n)] g = [[h[j][i]-m for j in range(i)]+[h[i][j]-m for j in range(i, n)] for i in range(n)] return g def prim(g): print '-'*48, '\nFunc:', sys._getframe().f_code.co_name s = [0] v = range(1, len(g)) es = [] t = 0 for i in range(len(g) - 1): min = 99999 for r in v: for d in s: if g[r][d] < min: min = g[r][d] j = r e = (r, d) s.append(j) v.remove(j) es.append(e) t += min print s, v, es print es, t def kruskal(g): size = len(g) print '-'*48, '\nFunc:', sys._getframe().f_code.co_name parts = [[i] for i in range(len(g))] es = [(g[i][j], i, j) for i in range(size) for j in range(i+1,size)] es.sort() te = [] t = 0 for e in es: for part in parts: if e[1] in part: p1 = part if e[2] in part: p2 = part if p1 != p2: p = p1.extend(p2) parts.remove(p2) te.append(e) t += e[0] #print parts, te print te, t g = graph(9, 9) for r in g:print r #prim(g) kruskal(g)
Python
b=r''' a="b=r"+"'"*3+b+"'"*3 print a+b open('tmp', 'w').write(a+b) ''' a="b=r"+"'"*3+b+"'"*3 print a+b open('tmp', 'w').write(a+b)
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 05 17:08:28 CST 2009 import random, sys sys.stdout=sys.stderr size=18 dim=3 k=3 pts=[[random.randint(-9,9) for i in range(dim)] for j in range(size)] print pts s = [None]*3 for i in range(k): s[i] = [p for p in pts[i]] print s clast = None while True: cluster = [[] for i in range(k)] for i in range(size): p = pts[i] dmin = None for c in range(k): d = 0 for j in range(dim): d += (p[j] - s[c][j]) ** 2 if dmin is None or d < dmin: dmin = d cc = c cluster[cc].append(i) print clast, cluster if cluster == clast: break clast = [[e for e in c] for c in cluster] raw_input() for i in range(k): s[i] = [0]*dim for j in range(dim): s[i][j] = sum(pts[i][j] for i in cluster[i]) / len(cluster[i]) print s print cluster
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 04 10:41:19 AM CST 2009 import random def NF(objs): cnt = 1 blank = 1 for w in objs: if w < blank: blank -= w else: cnt += 1 blank = 1 - w print cnt def FF(objs): boxs = [] for w in objs: done = False for i in range(len(boxs)): if w < boxs[i]: boxs[i] -= w done = True break if not done: boxs.append(1-w) print len(boxs) objs = [random.random() for i in range(1000)] NF(objs) FF(objs) FF(sorted(objs)) FF(sorted(objs, reverse=True))
Python
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date Jan 05 20:27:18 CST 2009 import random def random_shuffle(a): size = len(a) for i in range(size-1): t = a[i] s = random.randint(i+1, size-1) a[i] = a[s] a[s] = t def jc(a, b): sa = set(a) sb = set(b) r = .0 + len(sa.intersection(sb)) r /= len(sa.union(sb)) return r def shingle(a, w): size = len(a) s = set([]) for i in range(size-w+1): s.add(tuple(a[i:i+w])) return list(s) x = [1,2,3,4,5]*55 y = [1,2,3,4,5]*55 random_shuffle(x) random_shuffle(y) xx = shingle(x, 3) yy = shingle(y, 3) import md5 xm = [md5.new(str(e)).hexdigest() for e in xx] ym = [md5.new(str(e)).hexdigest() for e in yy] print len(xx) print len(yy) print jc(xx,yy) print jc(xm,ym) cnt = 0 n = 10000 for i in range(1000): size = min(len(xx), len(yy)) #pi = random.sample(range(n), n) #am = [pi[int(e, 16)%n] for e in xm] #bm = [pi[int(e, 16)%n] for e in ym] d = random.randint(1000000, 2000000) am = [int(e, 16) % d for e in xm] bm = [int(e, 16) % d for e in ym] if min(am) == min(bm): cnt += 1 print cnt
Python