How can I get the value of an intSliderGrp defined inside a class and use it on a function outside said class?
I'm trying to get my main UI all inside a class so I can just call it inside maya, but I need the value set on a slider to modify a function outside the classUI:
import maya.cmds as cmds
def setSubdivision(*args):
obj = cmds.ls(sl = True)
asubd = cmds.intSliderGrp(sliderSet, query = True , value = True)
for i in obj:
cmds.setAttr('%s.aiSubdivIterations' %i, int(asubd))
class subdivisionUI():
windowName = "ArnoldSubdivisionWindow"
def show(self):
if cmds.window(self.windowName, query = True, exists = True, width = 150):
cmds.deleteUI(self.windowName)
cmds.window(self.windowName)
mainColumn = cmds.columnLayout(adjustableColumn = True)
cmds.text(l='Set subdivisions to selected objects', al = 'center')
column2 = cmds.rowLayout(numberOfColumns = 2, adjustableColumn=2, columnAlign=(1, 'right'))
sliderSet = cmds.intSliderGrp(l = "Subdivisions", s =1, min = 0, max = 20, field = True)
b = cmds.button(l = 'Set')
cmds.button(b, e = True , command = setSubdivision, width = 50 )
cmds.showWindow()
subdivisionUI().show()
It's my first time using classes so I'm still trying to understand how they work and the proper use.
At the moment you do not use the advantage of classes for UI creation in Maya. The big advantage is that you can keep everything encapsulated in this class without the need of any external functions or global variables. If you try this approach your problem disappears:
import maya.cmds as cmds
class subdivisionUI():
windowName = "ArnoldSubdivisionWindow"
def __init__(self):
if cmds.window(self.windowName, query = True, exists = True, width = 150):
cmds.deleteUI(self.windowName)
self.window = cmds.window(self.windowName)
mainColumn = cmds.columnLayout(adjustableColumn = True)
cmds.text(l='Set subdivisions to selected objects', al = 'center')
column2 = cmds.rowLayout(numberOfColumns = 2, adjustableColumn=2, columnAlign=(1, 'right'))
self.sliderSet = cmds.intSliderGrp(l = "Subdivisions", s =1, min = 0, max = 20, field = True)
b = cmds.button(l = 'Set')
cmds.button(b, e = True , command = self.setSubdivision, width = 50 )
def setSubdivision(self, *args):
obj = cmds.ls(sl = True)
asubd = cmds.intSliderGrp(self.sliderSet, query = True , value = True)
for i in obj:
cmds.setAttr('%s.aiSubdivIterations' %i, int(asubd))
def show(self):
cmds.showWindow(self.window)
subdivisionUI().show()
Related
I'm having a problem with delivering a variable value to a function inside a class.
The specific issue occurs in the following code:
#discord.ui.select(
row = 0,
options = self.r
)
Here is the relevant code for the class:
class MyView(discord.ui.View):
def __init__(self, no):
super().__init__()
self.no = no
self.manga = None
self.chapters = None
self.startnum = -25
self.endnum = 0 # add 25
self.twentyfives = 0
self.r = []
r = []
for i in data:
if str(i["MangaName"]).lower() == no:
self.manga =i
break
if self.manga != None:
self.chapters = int(self.manga["ChaptersNumber"])
self.twentyfives = (self.chapters // 25)+1
self.startnum += 25
if self.endnum + 25 > self.chapters:
self.endnum = self.chapters
else:
self.endnum +=25
self.startnum +=25
for title in range(self.startnum,self.endnum):
self.r.append(discord.SelectOption(
label=self.manga["Chaptersinfo"][title]))
r = self.r
#discord.ui.select(
row = 0,
options = self.r
)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
manga_selected = select.values[0]
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")
i tried using different function to store the data then receive it again but it didn't work
and i tried to let
async def select_callback
and
#discord.ui.select
inside the class but the async def select_callback didn't work and the options didn't show
I am trying to use variables from one class in another. I'm not sure how to get rid of this problem. I want to be able to do this, does anyone have any suggestions. The error I'm getting is: AttributeError: 'MCNode' object has no attribute 'board'
class StudentAI():
def __init__(self,col,row,p):
self.col = col
self.row = row
self.p = p
self.board = Board(col,row,p)
self.board.initialize_game()
self.color = ''
self.opponent = {1:2, 2:1}
self.color = 2
class MCNode():
parent = None
boardstate = None
gameboard = None
col = 0
row = 0
p = 0
children = []
color = 2
# whitewon = 0
# blackwon = 0
wins = 0
game_color = 0
depth = 0
maxdepth = 15
visits = 0
c = math.sqrt(2)
opponent = {1:2,2:1}
def __init__(self, boardstate, gameboard, col, row, color, game_color, parent=None):
if parent != None:
self.parent = parent
self.depth = parent.depth + 1
self.children = []
self.col = col
self.row = row
# boardstate will be static copy of board stored in every node
self.boardstate = boardstate
# gameboard will be the board which constantly changes
self.gameboard = gameboard
self.game_color = game_color
self.color = color
# self.whitewon = 0
# self.blackwon = 0
self.wins = 0
self.visits = 0
self.maxdepth = 15
self.opponent = {1:2,2:1}
In a function inside the class McNode, I'm trying to do:
"current_piece = self.board.board[c][r]"
but I'm getting the error "AttributeError: 'MCNode' object has no attribute 'board'"
Does anyone have any suggestions as to how I can tweak this code to do what I'm trying to do?
Hi I'm having a problem in this classes I created the parent class extracao_nia with the method aplica_extracao for having the similar part of the execution that I use in others class and the diferent part is in the transform method definined in the children class
but I'm having an issue that the variables that I defined as list() are Null variable when I execute the code:
AttributeError: 'NoneType' object has no attribute 'append'
class extracao_nia:
def __init__(self, d=1, h=1, m=15):
self._data_base = "database"
self.UM_DIA = datetime.timedelta(days=d)
self.UMA_HORA = datetime.timedelta(hours=h)
self.INTERVALO = datetime.timedelta(minutes=m)
#property
def data_base(self):
return self._data_base
def aplica_extracao(self, SQL):
fim_intervalo = self.inicio + self.INTERVALO#
pbar = self.cria_prog_bar(SQL)#
while (fim_intervalo <= self.FIM):#
self.connector.execute(SQL,(self.inicio.strftime('%Y-%m-%d %H:%M'),fim_intervalo.strftime('%Y-%m-%d %H:%M')))#
for log in self.connector:#
self.transforma(log)
self.inicio = fim_intervalo
fim_intervalo = self.inicio + self.INTERVALO
class usuarios_unicos(extracao_nia):
def __init__(self, d=1, h=1, m=15, file='nodes.json'):
self._data_base = "database"
self.UM_DIA = datetime.timedelta(days=d)
self.UMA_HORA = datetime.timedelta(hours=h)
self.INTERVALO = datetime.timedelta(minutes=m)
self.file = file
self.ids = list()
self.nodes = list()
self.list_cpf = list()
def transforma(self, log):
context = json.loads(log[0])['context']
output = json.loads(log[0])['output']
try:
nr_cpf = context['dadosDinamicos']['nrCpf']
conversation_id = context['conversation_id']
nodes_visited = output['output_watson']['nodes_visited']
i = self.ids.index(conversation_id)
atual = len(self.nodes[i])
novo = len(nodes_visited)
if novo > atual:
nodes[i] = nodes_visited
except KeyError:
pass
except ValueError:
self.ids.append(conversation_id)
self.nodes = self.nodes.append(nodes_visited)
self.list_cpf = self.list_cpf.append(nr_cpf)
list.append returns None since it is an in-place operation, so
self.nodes = self.nodes.append(nodes_visited)
will result in self.nodes being assigned None. Instead you can just use
self.nodes += nodes_visited
I am trying to call a function from within a function, and the former calls more functions etc.
import ROOT as root
import sys, math
class SFs():
def __init__(self):
self.get_EfficiencyData = None
self.get_EfficiencyMC = None
self.get_ScaleFactor = None
self.eff_dataH = None
self.eff_mcH = None
self.get_ScaleFactor = None
self.get_EfficiencyMC = None
def ScaleFactor(self,inputRootFile):
self.eff_dataH = root.std.map("string", root.TGraphAsymmErrors)()
self.eff_mcH = root.std.map("string", root.TGraphAsymmErrors)()
EtaBins=["Lt0p9", "0p9to1p2","1p2to2p1","Gt2p1"]
fileIn = root.TFile(inputRootFile,"read")
HistoBaseName = "Label"
etaBinsH = fileIn.Get("Bins")
# etaLabel, GraphName
nEtaBins = int(etaBinsH.GetNbinsX())
for iBin in range (0, nEtaBins):
etaLabel = EtaBins[iBin]
GraphName = HistoBaseName+etaLabel+"_Data"
print GraphName,etaLabel
self.eff_dataH[etaLabel]=fileIn.Get(str(GraphName))
self.eff_mcH[etaLabel]=fileIn.Get("histo")
print self.eff_mcH[etaLabel].GetXaxis().GetNbins()
print self.eff_mcH[etaLabel].GetX()[5]
self.get_ScaleFactor(46.8,2.0)
def get_ScaleFactor(self,pt, eta):
efficiency_mc = get_EfficiencyMC(pt, eta)
if efficiency_mc != 0.:
SF = 1/float(efficiency_mc)
else:
SF=1.
return SF
def get_EfficiencyMC(self,pt, eta):
label = FindEtaLabel(eta,"mc")
# label= "Lt0p9"
binNumber = etaBinsH.GetXaxis().FindFixBin(eta)
label = etaBinsH.GetXaxis().GetBinLabel(binNumber)
ptbin = FindPtBin(eff_mcH, label, pt)
Eta = math.fabs(eta)
print "eff_mcH ==================",eff_mcH,binNumber,label,ptbin
# ptbin=10
if ptbin == -99: eff =1
else: eff= eff_mcH[label].GetY()[ptbin-1]
if eff > 1.: eff = -1
if eff < 0: eff = 0.
print "inside eff_mc",eff
return eff
sf = SFs()
sf.ScaleFactor("Muon_IsoMu27.root")
I want to call the get_ScaleFactor() which in turn calls the get_EfficiencyMC() etc, but I once trying calling the former, I get TypeError: 'NoneType' object is not callable
in your class init you define:
self.get_EfficiencyMC = None
and later define a function (i.e. class method)
def get_EfficiencyMC(self,pt, eta):
when you create an instance of the class, the init part is executed shadowing the class method. Just either remove it from the init, or change the method name.
I made a class to work with Heating wires:
class Heating_wire:
def __init__(self, ro, L,d,alpha):
self.ro = ro
self.L = L
self.d = d
self.alpha = alpha
self.RT = [1]
self.vector_T = [1]
def get_R20(self):
self.R_20 = self.ro*self.L/(np.pi*(self.d/2)**2)
def calcular_RT(self,vector_temp):
self.vector_T = vector_temp
self.RT = [self.R_20*(1 + temp*self.alpha) for temp in vector_temp ]
return self.RT
instantiate some objects:
kantal = Heating_wire(1.45,0.25,0.3,4e-5)
nicromo = Heating_wire(1.18,0.25,0.3,0.0004)
ferroniquel = Heating_wire(0.86,0.25,0.3,9.3e-4)
wires = [kantal,nicromo,ferroniquel]
And made a plot:
leg = []
vector_temp = np.linspace(20,1000,1000)
for wire in sorted(wires):
wire.get_R20()
wire.get_RT(vector_temp)
line, = plt.plot(wire.vector_T,wire.RT)
leg.append(line)
plt.legend(leg,sorted(wires))
The issue is that I'm not getting the right names in the legend but the reference to the objects:
If I add a name attribute
def __init__(self,name, ro, L,d,alpha):
self.name = name
I can append the names
leg = []
names= []
vector_temp = np.linspace(20,1000,1000)
for wire in sorted(wires):
wire.get_R20()
wire.get_RT(vector_temp)
line, = plt.plot(wire.vector_T,wire.RT)
leg.append(line)
names.append(wire.name)
plt.legend(leg,names,loc='best')
But I wonder if there is a simpler way t solve this using directly the names of the objects in the list of wires:
kantal = Heating_wire(1.45,0.25,0.3,4e-5)
nicromo = Heating_wire(1.18,0.25,0.3,0.0004)
ferroniquel = Heating_wire(0.86,0.25,0.3,9.3e-4)
wires = [kantal,nicromo,ferroniquel]
Just do it like this and there's no duplication:
wires = [
Heating_wire("kantal", 1.45,0.25,0.3,4e-5),
Heating_wire("nicromo", 1.18,0.25,0.3,0.0004),
Heating_wire("ferroniquel", 0.86,0.25,0.3,9.3e-4)
]
To answer your question, no, objects cannot access the names they were given.