Maya Python Assistance requested: connect attributes based on textfield contents - python

Background:
So thanks to the help of the user Theodox I was able to figure out how to create nodes in the node editor with name prefixs based on the joint you load into the selection field.
However: I want to take it a step further and make it so not only are the nodes created with joint name prefixes: but they will also connect the translates of the nodes created via connectAttr.
The problem?
I currently lack the knowledge to make this work and I cant find anything online, so any assistance would be most appreciated
Code:
I've tried lines of code like:
cmds.connectAttr( sel[0] + '.rotate', sel[1] + '.rotate' )
or
cmds.connectAttr( n=text_value +'_firstGuy', n=text_value +'_secondGuy' )
I know I can create seperate textfields and buttons to load the nodes and connect them thatway, but with the shortcut I'm coding, all the nodes I've created would be too many to load so it would be easier if I could just create the nodes with their connections, I'll post the code below for anyone willing to take a crack at it:
import maya.cmds as cmds
if cmds.window(window, exists =True):
cmds.deleteUI(window)
window = cmds.window(title='DS Node Connector demo')
column = cmds.columnLayout(adj=True)
def set_textfield(_):
sel = cmds.ls(selection=True)
cmds.textField(sld_textFld, edit=True, text=sel[0])
def nodebuilder(_):
text_value = cmds.textField(sld_textFld, q = True, text=True)
if text_value:
print "created:", cmds.createNode( 'transform', n=text_value +'_firstGuy' )
print "created:", cmds.createNode( 'transform', n=text_value +'_secondGuy' )
# Connect the translation of two nodes together
print "connected:", cmds.connectAttr (sel[0] +'.t', sel[1] + '.t')
#print "connected:", cmds.connectAttr( '_firstGuy.t', '_secondGuy.translate' )
# Connect the rotation of one node to the override colour
# of a second node.
#print "connected:", cmds.connectAttr( '_firstGuy.rotate', '_secondGuy.overrideColor' )
else:
cmds.warning("select an object and add it to the window first!")
sld_textFld = cmds.textField('sld_surfaceTextHJ', width =240)
load_button = cmds.button( label='Load Helper Joint', c = set_textfield)
node_button = cmds.button( label='Make Node', c = nodebuilder)
cmds.showWindow(window)
My expected result:
Upon hitting "make node" after loading a joint after hitting "load helper joint" that once "_firstGuy" and "_secondGuy" are created with the name prefix of the joint, that their translates will be connected. It helps to have the node editor open to test this.

Okay, you want to connect the translate attributes of the two new created nodes.
Usually connecting attributes works like this:
connectAttr(<attributeA>, <attributeB>)
Where attributeA is something like "NodeA.translate". So what you need is the name of your first node and the attribute name, in your case:
nodeNameA = text_value + "_firstGuy"
nodeNameB = text_value + "_secondGuy"
The attribute is the well known "translate", so the full attribute name would be:
attributeNameA = nodeNameA + ".translate"
attriubteNameB = nodeNameB + ".translate"
And the full command is now:
connectAttr(attributeNameA, attributeNameB)
The only problem here is that Maya automatically renames objects if there is already one with the same name. So a more save way it to use the created name this way:
firstGuyNode = cmds.createNode( 'transform', n=text_value +'_firstGuy' )

Related

Neo4j: Why can`t I find a particular node by find_one in python?

I am new to use Neo4j in python2.7. Now I have tried an easy test about Neo4j, but I can`t find the particular node in the database. The Node is existed, but the return result is 'None'.
Here are my codes:
from py2neo import Graph,Node,Relationship
test_graph = Graph(
"http://localhost:7474",
username="neo4j",
password="******"
)
test_node_1 = Node(label = "Person",name = "test_node_1")
test_node_2 = Node(label = "Person",name = "test_node_2")
test_graph.create(test_node_1)
test_graph.create(test_node_2)
node_1_call_node_2 = Relationship(test_node_1,'CALL',test_node_2)
node_2_call_node_1 = Relationship(test_node_2,'CALL',test_node_1)
test_graph.create(node_1_call_node_2)
test_graph.create(node_2_call_node_1)
find_code_1 = test_graph.find_one(
label="Person",
property_key="name",
property_value="test_node_1"
)
print (find_code_1)
The problem is that your syntax for the Node is slightly off. You're setting a property called label with the value Person, you're not creating Person nodes.
Here's what the syntax should be like :
test_node_1 = Node("Person",name = "test_node_1")
test_node_2 = Node("Person",name = "test_node_2")
Hope this helps.
Regards,
Tom

Arcpy.python ArcServer sde permissions

I have this python script that basically selects a point by it's ID, then selects all points within a distance and returns only a subset of those that match the type field. i.e. find all hospitals within 3 miles of this location..
My python script works, does what it's supposed to. So I create a GP service from it. Add the service back into the map and run it. Now I notice no matter what distance I use, the data doesn't change. If I delete the created Featureclass to see if it's really working. It does not create a new featureclass but it says it completed successfully.
Now the weird part, if I hit the GP service at the rest endpoint with the parameters it says it works but returns no records. I've been careful to avoid schema locks when using the Rest endpoint ArcMap and ArcCatalog are closed.
It's like the GP service doesn't have permission to write to the sde database, However my sde connection works fine on my PC.
Any ideas?
import arcpy, os, string
from arcpy import env
db = r"Connection to racdev1.sde"
theworkspace = r"Connection to racdev1.sde"
arcpy.env.workspace = theworkspace
arcpy.env.overwriteOutput = True
#facilityID = '1249'
facilityID = arcpy.GetParameterAsText(0)
#facilityIDType= 'PFI'
facilityIDType = arcpy.GetParameterAsText(1)
thedistance = arcpy.GetParameterAsText(2)
#thedistance = '3 miles'
#withindistance = "3 Miles"
withindistance = thedistance + ' Miles'
sql_query = "\"%s\" = '%s'" % ("ID", facilityID)
sql_query2 = "\"%s\" = '%s'" % ("IDTYPE", facilityIDType)
# Local variables:
Facilities = "DOHGIS.NYSDOH_CI_DATA"
featLayer = "thePts"
arcpy.MakeFeatureLayer_management(Facilities, featLayer)
# Process: Select Layer By Attribute
arcpy.SelectLayerByAttribute_management(featLayer, "NEW_SELECTION", sql_query)
# Process: Select Layer By Location 311
arcpy.SelectLayerByLocation_management(featLayer, "WITHIN_A_DISTANCE",featLayer, withindistance, "NEW_SELECTION")
#print " now for the subset"
arcpy.SelectLayerByAttribute_management("thePts", "SUBSET_SELECTION", sql_query2 )
# creaate the new featureclss..
arcpy.CopyFeatures_management("thePts",'DOHGIS.NYSDOH_FacilitiesQuery')
#print "Done"

How to instantiate an ontology using rdflib?

I have an ontology where I have defined series of classes, subclasses and properties. Now I want to automatically instantiate the ontology with Python code and save it in RDF/XML again and load it in Protege. I have written the following code:
def instantiating_ontology(rdf_address):
from rdflib import *
g = Graph()
input_RDF = g.parse(rdf_address)
#input_RDF = g.open(rdf_address, create=False)
myNamespace="http://www.semanticweb.org/.../ontologies/2015/3/RNO_V5042_RDF"
rno = Namespace(myNamespace+"#")
nodeClass = URIRef(rno+"Node")
arcClass = URIRef(rno+"Arc")
#owlNamespace = 'http://www.w3.org/2002/07/owl#NamedIndividual'
namedIndividual = URIRef('http://www.w3.org/2002/07/owl#NamedIndividual')
rdftype = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
for i in range(0,100):
individualName = rno + "arc_"+str(arcID)
#arc_individual= BNode(individualName)
arc_individual = BNode()
#g.add()
#g.add((arc_individual,rdftype, namedIndividual))
g.add((arc_individual,rdftype, arcClass))
g.add((arc_individual,rdftype, arcClass))
#g.commit()
output_address ="RNO_V5042_RDF.owl"
g.serialize(destination = output_address)
The file contains the added triples to the rdf/xml:
<rdf:Description rdf:nodeID="N0009844208f0490887a02160fbbf8b98">
<rdf:type rdf:resource="http://www.semanticweb.org/ehsan.abdolmajidi/ontologies/2015/3/RNO_V5042#Arc"/>
but when I open the file in Protege there are no instances for the classes.
Can someone tell me if the way I defined instances is wrong or I should use different tags?
After playing around with the code and the results, I realized that the notion rdf:nodeID should be replaced with rdf:about. to do so I only needed to change
for i in range(0,100):
individualName = rno + "arc_"+str(arcID)
#arc_individual= BNode(individualName)
arc_individual = BNode() #---> remove this one
arc_individual = URIRef(individualName) #----> add this one
g.add((arc_individual,rdftype, arcClass))
g.add((arc_individual,rdftype, arcClass))
arc_individual = URIRef(individualName)
that might seem easy but took me sometime to understand. I hope this can help others. :D

Prepending nightmare

I wrote some code to connect with FileMaker Server and ask for a new record to be created on the backend server. This portion works fine and the result contains unexpected text that does not show up in a browser. I couldn't get the find operations to work by looking at the tree in a browser so I ended up printing the tags and attributes out and every tag attribute pair has this format:
Tag: {http://www.filemaker.com/xml/fmresultset}error Attrib: {'code': '0'}
In my code below I'm having to put the fully qualified tag into the code to get the first find to work. This makes it harder to figure out the xPath to the object that I want to get from the XML. The second find below doesn't work since I can't figure out the path. The path should be /resultset/record/ and the attribute is record-id. Anybody have an idea of what is happening. Why is the fmresultset document prepended to every tag?
url = self.getBaseURL( machineID, file, lay ) + fields + "&-new"
result = self.sendURL( url )
import xml.etree.ElementTree as ET
root = ET.fromstring(result)
self.printXML( root )
base = "{http://www.filemaker.com/xml/fmresultset}"
find = root.find( base + "error" )
error = find.attrib[ 'code' ]
recID = 0
if ( error == '0' ):
find = root.find( base + "resultset" + base + "/record" )
recID = find.attrib[ 'record-id' ]
Keith
OK... You mentioned the word namespace and I figured it out. This uses the element version of root.
def getXMLValue( self, root, path, value ):
ns = {'fmrs': 'http://www.filemaker.com/xml/fmresultset' }
find = root.find( path, ns )
value = find.attrib[ value ]
return value
def getError ( self, root ):
return self.getXMLValue ( root, "fmrs:error", 'code' )
def getRecID ( self, root ):
return self.getXMLValue ( root, "fmrs:resultset/fmrs:record", 'record-id' )
This code correctly returns the correct value. I was expecting something like. Create an instance of the class then call setNamespace(). I'm having to put all these references to fmrs which I would rather not do but this solves the issues and the code isn't horrible to read.
Thanks for the assist.
-keith

Arcpy SelectLayerByLocation giving an error

this script is supposed to select features within distance in two layers based on some their characteristics one feature will get a score (example: water pipes crossing naturally sensitive areas like rivers, the type of that river and its permanency matter in the scoring, so each type will be selected then used in select by lactation function to give water pipes that are within a distance its score
this is the error I get when i run these codes:
Executing: SelectLayerByLocation water_mains WITHIN_A_DISTANCE Just_selected "2.5 Meters" NEW_SELECTION
Start Time: Thu Sep 25 15:21:09 2014
ERROR 999999: Error executing function.
A column was specified that does not exist.
A column was specified that does not exist.
Failed to execute (SelectLayerByLocation).
the select layer by location is in a script that is called by another script (main script)
the main script :
def main():
try:
import arcpy
from arcpy import env
# pathing to avoid retyping
env.workspace = "C:/Users/abusheikan/Desktop/prev_files/RiskAnalysisModel"
dataPath = 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\ToolData2'
arcpy.env.overwriteOutput = True
import imp
##Defines INPUT variables
#some variable wont be used but are there for future use, I'm starting off as simple as possible
creekLayer = dataPath + "\\ENVIRONMENTAL\\OHN_WaterCourse.shp"
PipeLayer=dataPath + "\\SERVICES\\water_mains.shp"
nameField = 'ROW_1'
scoreField = 'ROW_SCORE1'
crossingField = 'CROSS_ROW1'
ROWfield = 'ROW_TRUE1'
diaField='INTERNAL_D'
rangeVal= 416
Field = 'WARTERCOURS'
Field2='PERMANENCY'
arcpy.MakeFeatureLayer_management(PipeLayer,"water_mains")
inFeatures = "water_mains"
#The following lists contain road classes. Format is (a, b, c,d) such that a is the creek class name,
#b is an average permencnacy of flow, c is the width, nd d is the xscore to be given .
#Lower value of c means lower criticality.
creeks = [('Vertual Flow','intermittent',10,1),
('Vertual Connector','intermittent', 10,2),
('Vertual Flow','Permanent', 10,1),
('Vertual Connector', 'Permanent', 10,2),
('Ditch','Intermittent',5,3),
('Ditch','Permanent',5,4),
('Stream','Intermittent',5,3),
('Stream','Intermittent',5,4)]
## the following isnt used yet
creeks2 = [('Vertual Flow','intermittent',10,1),
('Vertual Connector','intermittent', 10,2),
('Vertual Flow','Permanent', 10,1),
('Vertual Connector', 'Permanent', 10,2),
('Ditch','Intermittent',5,3),
('Ditch','Permanent',5,4),
('Stream','Intermittent',5,3),
('Stream','Intermittent',5,4)]
## This codeblock isnt utilized yet and will always return row_score, it is supposed to adjusts the value of ROW_SCORE
##based on whether the water main crosses a creek, by looking up the value in CROSS_ROW1 feild that is obtained later on
expression = "crossing(!CROSS_ROW1!,!ROW_SCORE1!)"
codeblock = """def crossing(crosses, row_score):
if crosses != 0:
return 5
else:
return row_score"""
except:
arcpy.AddError("Definitions failed")
arcpy.AddMessage(arcpy.GetMessages())
try:
## pathing to a funtion to be called
fpath = 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\Scripts\\'
## defining the function pathing we retyped anyway for debugging purpuses.
functions = imp.load_source('functions', 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\Scripts\\functions_creeks.py')
## check check :-p
arcpy.AddMessage("Funtions Loaded")
except:
arcpy.AddMessage("Functions not loaded")
try:
##Clear all selections, because otherwise commands will be applied only to selected features, why? I ont know pls explain where this is
## supposed to be used and where not to. THANKs!
arcpy.SelectLayerByAttribute_management(inFeatures, "CLEAR_SELECTION")
arcpy.AddMessage("Selected")
##This new field will show the road overlying the pipe. Default value of "no Creek" will be assigned.
arcpy.AddField_management(inFeatures, nameField, "TEXT")
arcpy.CalculateField_management(inFeatures, nameField, '"No Creek"')
##This field will contain a score for the highest creek class over the pipe.
## Default of 0 means no creeks
arcpy.AddField_management(inFeatures, scoreField, "SHORT")
arcpy.CalculateField_management(inFeatures, scoreField, 1)
arcpy.AddField_management(inFeatures, crossingField, "SHORT")
## arcpy.AddField_management(mainRoadLayer, ROWfield, "FLOAT",3,1)
## arcpy.CalculateField_management("t_Pavement_Line", ROWfield, expressionROW, "PYTHON_9.3", codeblockROW)
except:
#Report error
arcpy.AddError("Could not create new fields")
#Report error messages
arcpy.AddMessage(arcpy.GetMessages())
try:
## functions.roadclass_loop is a function that loops through all creek classes in
## a list, selects the water mains within a distance of each one, and assigns the
## appropriate score. Full script is in the called function.
## the following s a failed test so never mind that commented out line, it may ciome in handy so left it in there
## arcpy.MakeFeatureLayer_management(PipeLayer,
## "JUST_MADE",str(dialField) + " <= "+ str(rangeVal))
## calls creek_loop funtion() i think here is where the error is created pls check the inputs they may be where problem is! but i cant see anything wrong with them.
functions.roadclass_loop(creeks, creekLayer, Field, inFeatures, "WITHIN_A_DISTANCE",
nameField, scoreField)
arcpy.AddMessage("small pipes")
## same as b4 but with the second tuple list.
functions.roadclass_loop(creeks2, creekLayer, Field, inFeatures, "WITHIN_A_DISTANCE",
nameField, scoreField)
arcpy.AddMessage("BIG PIPES")
## functions.roadclass_loop(provincial, provincialLayer, Field3, inFeatures, "INTERSECT",
## "", crossingField)
## If the CROSS_ROW field has a nonzero value (i.e. if the water main crosses a large road)
## the road class score will be increased to 5(the maximum).
## inserts the scores into the
arcpy.CalculateField_management(inFeatures, scoreField, expression, "PYTHON_9.3", codeblock)
except:
arcpy.AddMessage("Could not run")
arcpy.AddMessage(arcpy.GetMessages())
if __name__== "__main__":
main()
the called function is:
def test():
## import arcpy
arcpy.AddMessage("This function works")
##def roadclass_loop(listOfClassTuples, sourceLayer, fieldName, targetLayer,
## outputField1, outputField2):
def roadclass_loop(listOfClassTuples, sourceLayer, fieldName, targetLayer, crossingType,
outputField1, outputField2):
import arcpy
from arcpy import env
env.workspace = "C:/data/"
##try:
for creekclass in listOfClassTuples:
(classname, Permanency, creekWidth, score) = creekclass
bufferDistance = creekWidth*0.5
try:
if crossingType == "INTERSECT":
stringBuffer = ""
else:
stringBuffer = "%s Meters" % str(bufferDistance)
except:
arcpy.AddMessage("its here")
arcpy.MakeFeatureLayer_management(sourceLayer, "Just_selected",
fieldName + "= '"+ classname + "'")
#arcpy.MakeFeatureLayer_management("Just_Selected", "JUST_SELECTED", FieldName2+" = '"+ Permanency + "'")
arcpy.SelectLayerByLocation_management(targetLayer, crossingType,
"Just_selected", stringBuffer, "NEW_SELECTION")
classname = classname.lower()
if outputField1!= "":
arcpy.CalculateField_management(targetLayer, outputField1, classname )
arcpy.CalculateField_management(targetLayer, outputField2, score )
arcpy.Delete_management("Just_selected")
arcpy.SelectLayerByAttribute_management(targetLayer, "CLEAR_SELECTION")
##except:
# arcpy.AddMessage("Function failed")
#arcpy.AddMessage(arcpy.GetMessages())
See this question on the GIS StackExchange: Points in Polygon Count: Error with arcpy.selectLayerByLocation_management . They made a mistake when calling MakeFeatureLayer_management, but the error was thrown by SelectLayerByLocation_management. You may have a similar situation.
In your case, are you confident that the feature class stored in dataPath + "\\ENVIRONMENTAL\\OHN_WaterCourse.shp" has a field called WARTERCOURS? Is there maybe a typo there? (The word WARTERCOURS caught my attention; Google says you're the first person on the Internet to use it.)
Is your listOfClassTuples, which is being fed by your creeks variable, supposed to be set of fields within your creekLayer (dataPath + "\ENVIRONMENTAL\OHN_WaterCourse.shp)?

Categories

Resources