Python count lines in file:
filename = raw_input('file? ')
file = open(filename)
lines = 0
for line in file:
lines += 1
print '%r has %r lines' % (filename, lines)
Python count lines in file:
filename = raw_input('file? ')
file = open(filename)
lines = 0
for line in file:
lines += 1
print '%r has %r lines' % (filename, lines)
#import <Foundation/Foundation.h>
// the interface
@interface Car : NSObject {
int wheels;
int doors;
}
-(void) setNumWheels: (int) w;
-(void) setNumDoors: (int) d;
-(void) print;
@end
// the implementation
@implementation Car
-(void) seNumWheels: (int) w{
wheels = w;
}
-(void) setNumDoors: (int) d{
doors = d;
}
-(void) print {
NSLog (@"My car has %i wheels and %i doors.", doors, wheels);
}
@end
// the program
int main(int argc, const char * argv[])
{
@autoreleasepool {
Car *myCar;
myCar = [Car alloc];
myCar = [myCar init];
[myCar seNumWheels:4 ];
[myCar setNumDoors:4];
[myCar print];
}
}
Expressions for transforming nodes via pixel values.
string $cubes2[] = `ls -type transform "newCube*"`;
for( $each in $cubes2) {
float $u = `getAttr($each + ".translateX")`;
float $v = `getAttr($each + ".translateZ")`;
float $capValueF[] = `colorAtPoint -o RGB -u (($u+40)/80) -v (($v+40)/80) file1`;
setAttr ($each + ".scaleY") (($capValueF[0]+$capValueF[1]+$capValueF[2])*10);
setAttr ($each + "Lam.incandescenceR") $capValueF[0];
setAttr ($each + "Lam.incandescenceG") $capValueF[1];
setAttr ($each + "Lam.incandescenceB") $capValueF[2];
}
flushUndo;
Free software and HDR images for CG lighting!
http://www.hdrlabs.com/sibl/index.html
Display all links in a particular WordPress links category, but hide the category title:
<?php wp_list_bookmarks('category=224&categorize=0&title_li='); ?>
Uses the wp_list_bookmarks function.
Simple workaround to setting the environment variable, so that you can import custom modules saved at the specified path.
import os,sys
sys.path.append('/path/to/modules/')
Else to set the environment variable on the Mac by adding:
export PYTHONPATH=/path/to/modules/
to the .bashrc file
A renaming script that I use to rename photos, rendered animation, or video frames. Warning, this script will rename your files! There is no undo. Use with care. Constructive comments about Python usage very welcome.
Will work on Unix-like operating systems, not sure about Windows.
# Python renamer script: creates a function called pyrename(). pyrename() will rename all files in a given folder.
# Usage: Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().
# Warning, this script will rename your files. There is no undo. Use with care.
def pyrename():
'Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().'
import os
#function to ignore the hidden . files in a directory. Note the use of the 'yield' keyword
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith('.'):
yield f
path = raw_input('path to folder?: ')
#get the files from the folder and put the filenames in a list called files
theFiles = listdir_nohidden(path)
files = []
for f in theFiles:
files.append(f)
#user supplied values
print 'Want to replace a character or string in your file names?'
want_to_replace = raw_input('Type y or n. Or to completely rename type w: ')
if want_to_replace == 'y':
replace = raw_input('Type the character or string that you want to replace (FYI can be a space!): ')
replace_with = raw_input('Type the character or string that you want to replace with: ')
elif want_to_replace == 'w':
replace = ''
replace_with = raw_input('Type new name: ')
else:
replace = ''
replace_with = ''
if want_to_replace != 'w':
want_numbers = raw_input('Want your files numbered? type y or n: ')
if want_numbers == 'y':
zeros = raw_input('Type the amount of padding zeros you need (using a single integer, like 4): ')
else:
zeros = 0
if want_to_replace == 'w':
zeros = raw_input('Type the amount of padding zeros you need (using a single integer, like "4"): ')
ext = raw_input('Please type the three letter extension you want to use ex: jpg (NOT the .): ')
#remove extension, put the filenames in a list called names
names = []
for f in files:
if f[-4] == '.':
names.append(f.replace(f[-4:], ''))
else:
names.append(f)
#add new names, add user supplied extension, put the filenames in a list called namesPlusEx
namesPlusEx = []
count = 0
for f in names:
if want_to_replace == 'w':
namesPlusEx.append(f.replace(f, replace_with)+ (('.%.')+zeros+('d'))% count +'.'+ ext)
elif want_to_replace != 'w' and want_numbers == 'y':
namesPlusEx.append(f.replace(replace, replace_with)+ (('.%.')+zeros+('d'))% count +'.'+ ext)
else:
namesPlusEx.append(f.replace(replace, replace_with)+'.'+ ext)
count += 1
#rename the actual files
c=0
for f in files:
os.rename(path+'/'+f, path+'/'+namesPlusEx[c])
c+=1
print 'You have re-named %d files' % len(files)
Maya Python script:
#Audio Driven Particle System 2011.10.27 A1
#Python for Maya
#Code By: Oliver Wolfson
#oliverwolfson.com - wolf@oliverwolfson.com
#You will need keyframes formatted in text files in an exclusive directory to make this work. See:
#http://oliverwolfson.com/animating-with-audio/ for more details
import os
import maya.cmds as mc
##LIGHT
Light = mc.spotLight(ca=120, n="mySpotLight")
mc.setAttr( ("mySpotLightShape.useDepthMapShadows"), 1)
mc.setAttr( ("mySpotLightShape.dmapResolution"), 2048)
mc.setAttr( ("mySpotLightShape.dmapFilterSize"), 6)
mc.setAttr( ("mySpotLightShape.penumbraAngle"), 10)
mc.setAttr( ("mySpotLightShape.dropoff"), 1)
mc.setAttr( ("mySpotLight.translateX"), 125)
mc.setAttr( ("mySpotLight.translateY"), 100)
mc.setAttr( ("mySpotLight.translateZ"), 20)
mc.setAttr( ("mySpotLight.rotateX"), -33)
mc.setAttr( ("mySpotLight.rotateY"), 10)
mc.setAttr( ("mySpotLight.rotateZ"), -45)
mc.setAttr( ("mySpotLight.scaleX"), 30)
mc.setAttr( ("mySpotLight.scaleY"), 30)
mc.setAttr( ("mySpotLight.scaleZ"), 30)
##AUDIO DRIVEN THING
num = 0
for p in range(0, 64, 2):
print("this is the " + str(num) + " num:" + str(p))
num += 1
Locator = mc.spaceLocator(n=("myLocator"+ str(num)))
Shader = mc.shadingNode('blinn', asShader = True)
mc.setAttr ((Shader+ ".glowIntensity"), .1)
SG = mc.sets (renderable=True, noSurfaceShader=True, empty=True)
mc.connectAttr((Shader +".outColor"), (SG + ".surfaceShader"))
mc.setAttr((Shader + ".color"),0.203189, 0.252033, 0.57554)
Plane = mc.polyPlane(h = 10, sw = 1, sh = 15, cuv = 2)
mc.setAttr(str(Plane[0]) + ".rotateX", 90)
mc.setAttr(str(Plane[0]) + ".scaleX", .25)
mc.makeIdentity( apply=True )
mc.hyperShade(assign = Shader)
mc.select(clear=True)
Emitter = mc.emitter (type = 'omni')
Particles = mc.particle()
mc.connectDynamic(Particles, em= Emitter )
mc.setAttr((Particles[1] + ".lifespanMode"), 1)
mc.select(Plane[0])
Wave = mc.nonLinear( type= 'wave' )
mc.setAttr((Wave[0] + ".wavelength"), .4)
mc.setAttr((Wave[0] + "Handle.rotateZ"), 90)
mc.setAttr((Wave[0] + "Handle.rotateY"), 50)
mc.setAttr((Wave[0] + "Handle.translateY"), -7)
mc.setAttr((Wave[0] + "Handle.translateZ"), 11)
mc.makeIdentity( apply=True )
mc.select(clear=True)
mc.particleInstancer( Particles[1], addObject = True, object = Plane[0], cycle='None', cycleStep=1, cycleStepUnits='Frames', levelOfDetail='Geometry', rotationUnits='Degrees', rotationOrder='XYZ', position='worldPosition', age='age')
mc.expression ( s = Wave[0] + ".offset = " + Locator[0] + ".translateY/10;\n" + Wave[0] + ".amplitude = " + Locator[0] + ".translateY/10;\n" + Wave[0] + "Handle.rotateX = frame;\n" + Wave[0] + "Handle.rotateZ = " + Locator[0] + ".translateY*0;\n" + Wave[0] + "Handle.scaleX =" + Locator[0] + ".translateY;\n" + Wave[0] + "Handle.scaleY = " + Locator[0] + ".translateY;\n" + Wave[0] + "Handle.scaleZ = " + Locator[0] + ".translateY;\n")
mc.expression ( s = Emitter[0] + ".translateY = " + Locator[0] + ".translateY;\n" + Emitter[0] + ".rate = " + Locator[0] + ".translateY*20;\n" + Emitter[0] + ".speed = " + Locator[0] + ".translateY;\n")
mc.expression ( s = Plane[0] + ".rotateY = " + Locator[0] + ".translateY*60;\n" + Plane[0] + ".translateY = " + Locator[0] + ".translateY;\n" + Plane[0] + ".scaleY = " + Locator[0] + ".translateY/;\n" + Plane[0] + ".rotateX = " + Locator[0] + ".translateY;\n")
mc.expression ( s = Shader + ".incandescenceR =" + Locator[0] + ".translateY/200;\n" + Shader + ".incandescenceG = " + Locator[0] + ".translateY/200;\n" + Shader + ".incandescenceB = " + Locator[0] + ".translateY/100;")
mc.select(Locator)
mc.select(Plane, add=True)
mc.select(Emitter, add=True)
mc.select(Wave , add=True)
mc.group(n= ("myGroup" + str(num)) )
mc.setAttr("myGroup" + str(num) + ".translateZ", p*-10)
mc.select(clear=True)
for l in range(1, 33, 1):
mc.select(("myLocator" + str(l)), add=True)
## add path to keyframe data files - just the source directory that contains them.
rootdir='/Volumes/2TB/work/3D/Maya/Maya_projects/Mogwai/sound/ranoPanoKeys01/zapped'
## "ty", in line 13, refers to the Maya attribute channel of the selected objects. Modify this attribute as necessary.
objs= mc.ls(sl=True)
for subdir, dirs, files in os.walk(rootdir):
for thisFile, o in zip(files, objs):
file = open((os.path.join(rootdir, thisFile)), 'r')
lines = file.readlines()
file.close()
for i in range(len(lines)):
mc.setKeyframe(o, at='ty', v=float(lines[i]), t=i, itt='linear', ott='linear')
Use this information to build key data for this script
http://oliverwolfson.com/extracting-raw-key-frame-data/
A simple program that will count the words and sentences in a text file. Sightly modified version of the code I found on daniweb.com.
# count lines, sentences, and words of a text file
# set all the counters to zero
lines, blanklines, sentences, words = 0, 0, 0, 0
# write the trs file
fname = "/path/filename.txt"
# read the file back in
textf = open(fname, "r")
# reads one line at a time
for line in textf:
#print line, # test
lines += 1
if line.startswith('\n'):
blanklines += 1
else:
# assume that each sentence ends with . or ! or ?
# so simply count these characters
sentences += line.count('.') + line.count('!') + line.count('?')
# create a list of words
# use None to split at any whitespace regardless of length
# so for instance double space counts as one space
tempwords = line.split(None)
#print tempwords # test
# word total count
words += len(tempwords)
textf.close()
print '-' * 50
print "Lines : ", lines
print "Blank lines: ", blanklines
print "Sentences : ", sentences
print "Words : ", words
Splashes created in Real Flow, and instanced to Maya Particles.
Ripples created with a dynamic fluid texture.
float $colU = particleShape1.collisionU;
float $colV = particleShape1.collisionV;
if ($colU > 0) {
int $xpos = fluidTexture2DShape1.resolutionW * $colU;
int $ypos = fluidTexture2DShape1.resolutionH * $colV;
setFluidAttr -xi $xpos -yi $ypos -at density -ad -fv 0.6 fluidTexture2DShape1;
particleShape1.lifespanPP=0;
}
Syntax Highlighter Evolved “short codes” or brush aliases for “brushes” brushes.
http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/
Ex: [c] code goes here [/c] for c code.
Create animated instances geometry at a particle collision.
For my raindrop splash, I am using an animated sequence of geometry, created in realflow (70mb). The realflow bin sequence is a single node after it is imported to Maya, it needs to be converted (duplicated) to a sequence of Maya nodes, multiple nodes. Use the following MEL script to convert the bin to multiple nodes.
//Select your realflow imported bin
string $bin[] = `ls-sl`;
//this is set up to to "convert" (duplicate) the bin from frame 1 - 100. Set the frame range that you want to convert below.
for( $index = 1; $index <= 100; $index++ )
{
currentTime $index;
select $bin[0];
duplicate;
select -cl ;
}
Now you should have a sequence of separate meshes, each representing a frame of your instanced animation. These will be loaded into the “particle instancer” to allow for animation at the point where each particle collides.
Create a collision event for your particle
1. Select particle and collision object and go to Menu : Particles > Make Collide
2. Set a particle collision event for your selected particle. Particles > Particle collision event editor. Set: event type to “emit”. Set: inherit to 0. Set: 1 particle emitted per collision. Set: Original Dies.
3.Press the create event button. A new particle object will be created.
Instance the geometry to the newly created particle.
1.Go to Menu>Particles > Instancer options
2. Load your sequence of separate meshes into the “Instanced Objects” section. Make sure that your particleShape is NOT loaded into the create instancer as an instanced object as it will try and instance itself.
3. Set: particle object to instance to : particleShape2 or whatever the particle object that was created by the collision event.
4. Select the newly created particle object shape. In the attribute editor, set: the lifespan of the particle to the duration of you splash object geometry sequence (number of individual nodes). The lifespan is in seconds…so you will need to do the math to get your frame count..
Rough guide:
float $colU = particleShape1.collisionU;
float $colV = particleShape1.collisionV;
if ($colU > 0) {
particleShape1.lifespanPP=0;
loc.translateX = ($colU*10);
loc.translateZ = ((1 - $colV) * 10);
}
Based on this tutorial. You will need to download and source this script.
—
I added attributes to the cubes: .col1(int), .theCol_u(int), and .vel(float) to watch for collisions, “unique” collisions (see the tutorial), and the velocity of the cube, respectively.
Two expressions are created for each cube, each rigidBody. The first is created to watch the dynamic rigid body collisions, and the velocity of the rigid body.
// variables
string $myRigidBody = "rigidBody1";
int $contactCount;
int $uniqueContactCount;
//check velocity
vector $theVelocity1 = `getAttr rigidBody1.velocity`;
float $velCheck1 = ($theVelocity1.x + $theVelocity1.y + $theVelocity1.z);
float $absVel = `abs $velCheck1`;
pCube1.vel = $absVel;
// get $contactCount
$contactCount = `getAttr($myRigidBody+".contactCount")`;
// compute theCol_u
if ($contactCount > 0)
{
string $array[] = `rigidBody -q -contactName $myRigidBody`;
string $flatArray[] = flattenStringArray($array);
$uniqueContactCount = size($flatArray);
}
else
{
$uniqueContactCount = 0;
}
// set interface attributes
pCube1.col1 = $contactCount;
pCube1.theCol_u = $uniqueContactCount;
The second expression affects a shader, based on the collision and velocity values collected by the expression above.
int $theTime = `currentTime -query`; if ($theTime > 0) if (myLam1.incandescenceR >.05) myLam1.incandescenceR = myLam1.incandescenceR -.075; else if (pCube1.vel > 0.2) if ( pCube1.theCol_u >=1) myLam1.incandescenceR = 2.5; else myLam1.incandescenceR = 0;
You can create this graphic equalizer with Trapcode Soundkeys and Maya. Use my Python script, below, to automatically import keyframe data and create the eq.
Trapcode Soundkeys, an Adobe After Effects plugin, breaks audio into into about 27 frequency blocks, “ranges”, and allows you to drive animation, set keyframes, or export keyframes. To export keys, copy the keyframes from the After Effects timeline, then paste into a text editor to create your data.txt files. Each frequency range should have it’s own text file, named sequentially. Use a code editor like BB Edit or Text Wrangler, as these apps will save your .txt files with UNIX line returns, which are necessary to make my Python script work properly.
Place all the data files in a directory, by themselves, and use the Python script below to automatically build the EQ in Maya.
## make a graphic equalizer, based on keyframe data from After Effects and Sound Keys.
import os
import maya.cmds as mc
## add path to keyframe data files - just the source directory that contains them.
rootdir='/path/to/data/folder'
theAttribute = 'data'
count = 0
theCubes = []
for subdir, dirs, files in os.walk(rootdir):
dataFiles = [each for each in files if each.endswith('.txt')]
for thisFile in dataFiles:
## create a cube for each data file, and distibute them across the X axis
mc.polyCube()
cube = mc.ls(sl = True)
cubeName=cube[0]
theCubes.append(cubeName)
mc.setAttr((cubeName + '.translateY'), .5);
mc.makeIdentity(apply=True, t =True, r=True, s=True, n= 0)
mc.ResetTransformations()
mc.move( count -(len(dataFiles)/2), 0, 0)
count +=1
count = 0
for subdir, dirs, files in os.walk(rootdir):
dataFiles = [each for each in files if each.endswith('.txt')]
for thisFile, o in zip(dataFiles, theCubes):
## prepare each cube for animation by ading an attibute to accept the keys, and creating an expression
theName = theCubes[count]
mc.addAttr( theName, shortName='data', longName='data', defaultValue=1.0)
mc.setAttr ( (theName + '.data'), e=True, keyable=True)
mc.expression(o=theName, s = (theName + '.scaleY =' + theName + '.data / 4'), ae = True, uc = all)
## make shader for each cube
myBlinn = mc.shadingNode('blinn', asShader=True, name = ("myBlinn" + str(count)))
myShader = mc.sets(renderable=True, noSurfaceShader=True, empty=True, name = ('myBlinn' + str(count) + 'SG'))
mc.connectAttr( (myBlinn + ".outColor"), (myShader + ".surfaceShader"), f=True)
mc.setAttr((myBlinn + ".color"), 0.1, 0.1, 0.1, type ='double3' )
mySetRange = mc.shadingNode('setRange', asUtility=True)
mySetRange2 = mc.shadingNode('setRange', asUtility=True)
mc.setAttr((mySetRange + ".minX"),230)
mc.setAttr((mySetRange + ".maxX") ,240)
mc.setAttr((mySetRange + ".oldMaxX") ,25)
mc.setAttr((mySetRange2 + ".maxX") ,3)
mc.setAttr((mySetRange2 + ".minX") ,.1)
mc.setAttr((mySetRange2 + ".oldMaxX") ,25)
myRamp = mc.shadingNode('ramp', asTexture=True)
my2dPlace = mc.shadingNode('place2dTexture', asUtility=True)
mc.connectAttr((my2dPlace + ".outUV"), (myRamp + ".uv"))
mc.connectAttr((my2dPlace + ".outUvFilterSize"), (myRamp + ".uvFilterSize"))
mc.setAttr((myRamp + ".colorEntryList[2].color"), 0, 0, 0 , type = 'double3')
mc.removeMultiInstance((myRamp + ".colorEntryList[0]"), b=True )
mc.removeMultiInstance(myRamp + ".colorEntryList[1]", b=True )
mc.connectAttr( (theName + ".scaleY"), (mySetRange + ".valueX"), f=True)
mc.connectAttr( (theName+ ".scaleY"), (mySetRange2 + ".valueX"), f=True)
mc.connectAttr( (theName + ".scaleY"), (mySetRange2 + ".valueY"), f=True)
mc.connectAttr( (theName + ".scaleY"), (mySetRange2 + ".valueZ"), f=True)
myhsvToRgb = mc.createNode('hsvToRgb', ss=True)
mc.setAttr((myhsvToRgb+".inHsv"), .75, .75, .75)
mc.connectAttr( (mySetRange + ".outValueX"), (myhsvToRgb + ".inHsvR"), f=True )
mc.connectAttr( (myRamp + ".outColor"), (myBlinn + ".incandescence"), f=True )
mc.connectAttr( (myhsvToRgb + ".outRgb"), (myRamp+ ".colorEntryList[2].color"), f=True )
mc.connectAttr( (mySetRange2 + ".outValue"), (myRamp + ".colorGain"), f=True )
mc.select(theName)
mc.sets( e=True, forceElement= myShader)
count +=1
## read keyframe data and set keyframes
dataFile = open((os.path.join(rootdir, thisFile)), 'r')
lines = dataFile.readlines()
dataFile.close()
mylines = lines[10:-4]
for eachLine in mylines:
data = eachLine.split('\t')
theFrame = data[1]
theValue = data[2]
mc.setKeyframe( o, v=float(theValue), at=theAttribute, t =float(theFrame))
## the code below will set the playback range to equal the amount of the keyframe data in the files
fileData = open(rootdir + '/' + dataFiles[0])
lines= fileData.readlines()
fileData.close()
myLines = lines[10:-4]
countLines = len(myLines)
mc.playbackOptions( minTime='0sec', maxTime=countLines)
These are fairly rudimentary python scripts, to export keys from Maya and import them back into Maya. Creates a key at every frame. May be interesting to people learning Python.
Export Maya Keys
import maya.cmds as mc
# Select all nodes with keys to export
# Customize the path below so that it points to, or creates, the file where you want to store the keyframe data
myFileObject=open('/mydataDir/data.txt', 'w')
obs = mc.ls(sl=True)
theData = []
minTime = mc.playbackOptions(query=True, minTime=True)
maxTime = mc.playbackOptions(query=True, maxTime=True)
attributes = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ', 'scaleX', 'scaleY', 'scaleZ', 'visibility']
for time in range(minTime -1, maxTime +1):
mc.currentTime(time)
count = 0
for selection in obs:
name = obs[count]
count +=1
for theAttribute in attributes:
myAtF = mc.getAttr(selection + '.' + theAttribute)
myAt = str(myAtF)
myTime = str(time)
theData.append(myAt + ' ' + myTime + ' ' + theAttribute + ' ' + name + ' \n')
for lines in theData:
myFileObject.writelines(lines)
myFileObject.close()
Import Maya Keys
This will import keys to nodes which are named identically to the nodes that were selected when the keys were exported.
import maya.cmds as mc
# Customize the path below so that it points to the file where you have exported the keyframe data
myFileObject=open('/mydataDir/data.txt', 'r')
theLines = myFileObject.readlines()
count = 0
for line in theLines:
theLine = theLines[count]
theSplit = str.split(theLine)
theValue = theSplit[0]
theFrame = theSplit[1]
theAttribute = theSplit[2]
theName = theSplit[3]
mc.setKeyframe( theName, v=float(theValue), at=theAttribute, t =float(theFrame))
count +=1
myFileObject.close()
pi = 3.14159265
print(pi)
# Result: 3.14159265 #
print("%.2f" % pi)
# Result: 3.14 #
round(pi,3)
# Result: 3.142 #
print("%.1f" % round(pi,0))
# Result: 3.0 #
SyntaxHighlighter Evolved allows you to easily post syntax-highlighted code to your WordPress powered site. Download the plugin here.
Code is styled with what they call a “brush”. See a list of syntax brushes here.
Ex: [c] code goes here [/c] for c code.
An example of C code, formatted and highlighted by the plugin.
/* sample C code */
#include <stdio.h>
main()
{
printf ("SyntaxHighlighter Evolved for WordPress \n");
return 0;
}
Example of a Python script , formatted and highlighted by SyntaxHighlighter, using the Python brush.
# Measure some strings:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
Example of a MEL script , formatted by SyntaxHighlighter, using the Plain Text brush, there is no MEL brush.
//random MEL script string $myString = "some random MEL"; print ($myString +"\n"); print (size($myString));