Select the right context for the OUTLINER using PYTHON and QT - python

I have the following code :
def make_override_editable():
for area in bpy.context.screen.areas:
if area.type == "OUTLINER":
ctx = bpy.context.copy()
ctx["area"] = area
with bpy.context.temp_override(area=area):
print(bpy.context.area.type)
bpy.ops.outliner.liboverride_operation(
type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",
selection_set="SELECTED_AND_CONTENT",
)
The following line when is ran through the script :
print(bpy.context.area.type)
outputs OUTLINER
but I still get the error that I have the incorrect context :
RuntimeError: Operator bpy.ops.outliner.liboverride_operation.poll() failed, context is incorrect
which normally works in blender text editor with 3 lines :
bpy.context.area.type = 'OUTLINER'
bpy.ops.outliner.liboverride_operation(type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",selection_set="SELECTED_AND_CONTENT")
bpy.context.area.type = 'TEXT_EDITOR'
I'm using python in a much more complex script with QT.
any suggestions ?
I'm trying to make a linked skeleton (Armature) editable so I can change it's pose.
I've also searched for a low level function that I can use, but did not had any success.
or perhaps is there another method to LINK and animation to a LINKED Armature ?
I've tried this :
def make_override_editable():
for area in bpy.context.screen.areas:
if area.type == "OUTLINER":
ctx = bpy.context.copy()
ctx["area"] = area
with bpy.context.temp_override(area=area):
print(bpy.context.area.type)
bpy.ops.outliner.liboverride_operation(
type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",
selection_set="SELECTED_AND_CONTENT",
)
And was expecting to have this
bpy.ops.outliner.liboverride_operation(type="OVERRIDE_LIBRARY_CREATE_HIERARCHY",selection_set="SELECTED_AND_CONTENT")

this works even if the Armature is linked.
no need to use operators.
# Reset the Armature to the default POSE.
for n in bpy.context.object.pose.bones:
n.location = (0, 0, 0)
n.rotation_quaternion = (1, 0, 0, 0)
n.rotation_axis_angle = (0, 0, 1, 0)
n.rotation_euler = (0, 0, 0)
n.scale = (1, 1, 1)

Related

Tkinter window does not load completely

I'm trying to have a progress window which shows the progress, alongside having tasks happening in the background. Everything works as expected, except the window partially loads on to the screen (how much of it does depends on every run). Here is the relevant part of the code:
def loading(): #Displays loading progress while setting up the exam
global load, progress
load = Toplevel()
load.title("Loading")
load.attributes('-topmost', True)
load.overrideredirect(True)
lab = Label(load, text = ("Preparing Your Exam, Please Wait!\nPlease DO NOT Open any Other Window.\n"
+"Doing so may lead to immidiate Termination."))
lab.grid(row = 0, column = 1, padx = 20, pady = 20)
progress=Progressbar(load,orient=HORIZONTAL,length=200,mode='determinate')
progress.grid(row = 1, column = 1, padx = 20, pady = 20)
log = Label(load, image = logo)
log.image = logo
log.grid(row = 0, column = 0, rowspan = 2, padx = 20, pady = 20)
w_req, h_req = load.winfo_width(), load.winfo_height()
w_form = load.winfo_rootx() - load.winfo_x()
w = w_req + w_form*2
h = h_req + (load.winfo_rooty() - load.winfo_y()) + w_form
x = (load.winfo_screenwidth() // 2) - (w // 2)
y = (load.winfo_screenheight() // 2) - (h // 2)
load.geometry(f'{w_req}x{h_req}+{x}+{y}')
Here's what happens after calling loading:
loading()
conv_th = Thread(target = Convert).start()
The Convert function converts and processes images, I'm not sharing that because it might not be relevant.
I far as I think, it might be because it is not getting enough time to load completely, but I couldn't really figure out what could be causing the program to behave this way. Any help will be appreciated!
Update: This behavior is seen even if conv_th = Thread(target = Convert).start() is omitted, implying that there could be a problem within the loading() function.
So, I ended up solving the problem myself. I'm telling the reason that I think is most probable, please correct me if the reason that I give is incorrect or there is another solution for this.
This part of the code,
w_req, h_req = load.winfo_width(), load.winfo_height()
w_form = load.winfo_rootx() - load.winfo_x()
w = w_req + w_form*2
h = h_req + (load.winfo_rooty() - load.winfo_y()) + w_form
x = (load.winfo_screenwidth() // 2) - (w // 2)
y = (load.winfo_screenheight() // 2) - (h // 2)
was being executed too early, before the window could actually load itself up completely, and hence whatever amount of it got loaded before this, was taken as the dimensions and then the values were set.
Adding the command load.update_idletasks() before the above part of the code resolved the problem. Thanks #martineau, your comment was really helpful in figuring this out.

Selecting Joints in hierarchy one at a time

I have this code
joint_name = cmds.ls(sl=1)[0]
circle_name = cmds.circle(name = joint_name + "_CTL", nr=(1, 0, 0) )
group_name = cmds.group(name = joint_name + "_OFFSET")
cmds.select(joint_name, group_name)temp_constraint = cmds.parentConstraint()
cmds.delete(temp_constraint)
cmds.select(circle_name, joint_name)
cmds.pointConstraint()
cmds.orientConstraint()
When you select a joint and run this code you will get a circle that will control that joint. While going down the hierarchy you have to select that joint and then run the code.
How would I be able to have all the joints to have circles controlling them without having to go through the outliner selection a joint?
run this on your chain of joint :
for x, joint_name in enumerate(cmds.ls(sl=1, dag=True, type='joint')):
circle_name = cmds.circle(name = '{}_CTL{:02d}'.format(joint_name,x), nr=(1, 0, 0) )
group_name = cmds.group(name = '{}_OFFSET{:02d}'.format(joint_name,x))
cmds.select(joint_name, group_name)
temp_constraint = cmds.parentConstraint()
cmds.delete(temp_constraint)
cmds.select(circle_name, joint_name)
cmds.pointConstraint()
cmds.orientConstraint()
Note that instead of use select, you could feed pointConstraint :
cmds.pointConstraint(circle_name, joint_name, n='something')

Python, C++ VTK Affine transformation

My first question here. I am working to a visualization pipeline with the vtk library (neuroimaging data). However, I am really struggling with the affine handling. From the documentation (example, doxygen, books) It seems I should use something like this:
transform = vtkTransform()
matrix_vtk =vtkMatrix4x4()
matrix_vtk.DeepCopy((1, 0, 0, 0, 0, 1, 0, 1, 0,0,1,0,0,0,0,1))
transform.SetMatrix(matrix_vtk)
transform_filter = vtkTransformPolyDataFilter()
transform_filter.SetTransform(transform)
dataset_mapper = vtk.vtkDataSetMapper()
dataset_mapper.SetInputConnection(transform_filter.GetOutputPort())
actor.SetMapper(dataset_mapper)
However the results are not those I expected :D
The complete code is:
from vtk import *
fname_trk = "test/L113619_imfs_d10_110mm.trk"
fname_vtk = "test/L113619_imfs_d10.vtk"
fname_ply = "test/113619_Lwhite.ply"
reader = vtkPLYReader()
reader.SetFileName(fname_ply)
reader_vtk = vtkPolyDataReader()
reader_vtk.SetFileName(fname_vtk)
ren = vtkRenderer()
wren = vtkRenderWindow()
iren = vtkRenderWindowInteractor()
wren.AddRenderer(ren)
iren.SetRenderWindow(wren)
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(reader.GetOutputPort())
mapper_vtk = vtkPolyDataMapper()
mapper_vtk.SetInputConnection(reader_vtk.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor_vtk = vtkActor()
# actor_vtk.SetMapper(mapper_vtk)
ren.AddActor(actor_vtk)
ren.AddActor(actor)
transform = vtkTransform()
matrix_vtk =vtkMatrix4x4()
matrix_vtk.DeepCopy((1, 0, 0, 0, 0, 1, 0, 1, 0,0,1,0,0,0,0,1))
transform.SetMatrix(matrix_vtk)
transform_filter = vtkTransformPolyDataFilter()
transform_filter.SetTransform(transform)
dataset_mapper = vtk.vtkDataSetMapper()
dataset_mapper.SetInputConnection(transform_filter.GetOutputPort())
actor.SetMapper(dataset_mapper)
actor.SetMapper(datasetmapper)
iren.Initialize()
iren.Start()
Any suggestions?
You didn't connect any input to filter, something like transform_filter.SetInputData(reader.GetOutputPort()).
It would be helpful if you could write what you expect.
your process is right, however, your output is not correctly defined. you can run it line by line and follow your output.

Openstack Permission denied when I generate a picture by python

I use a program which can generate a picture. I saved it by
img.save("/usr/lib/python2.6/site-packages/openstackdashboard/static/dashboard/img/validate.jpeg")
return strs # strs is picture's data
Everything goes right when run it alone . But " IOError " occured when I call it by
from .auth_code import Create_Validate_Code
auth_code_str = Create_Validate_Code()
And horizon says " [Errno 13] Permission denied: '/usr/lib/python2.6/site-packages/openstack-dashboard/static/dashboard/img/validate.jpeg' ". Could someone help me ? Thanks a lot .
This is all code to create a picture
#!/usr/bin/env python
import random
import Image, ImageDraw, ImageFont, ImageFilter
_letter_cases = "1234567890"
_upper_cases = _letter_cases.upper()
_numbers = ''.join(map(str, range(3, 10)))
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
fontType="/usr/share/fonts/lohit-tamil/Lohit-Tamil.ttf"
def create_lines(draw,n_line,width,height):
line_num = random.randint(n_line[0],n_line[1])
for i in range(line_num):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill=(0, 0, 0))
def create_points(draw,point_chance,width,height):
chance = min(100, max(0, int(point_chance)))
for w in xrange(width):
for h in xrange(height):
tmp = random.randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0))
def create_strs(draw,chars,length,font_type, font_size,width,height,fg_color):
c_chars = random.sample(chars, length)
strs = ' %s ' % ' '.join(c_chars)
font = ImageFont.truetype(font_type, font_size)
font_width, font_height = font.getsize(strs)
draw.text(((width - font_width) / 3, (height - font_height) / 3),strs, font=font, fill=fg_color)
return ''.join(c_chars)
def Create_Validate_Code(size=(120, 30),
chars=init_chars,
img_type="GIF",
mode="RGB",
bg_color=(255, 255, 255),
fg_color=(0, 0, 255),
font_size=18,
font_type=fontType,
length=4,
draw_lines=True,
n_line=(1, 2),
draw_points=True,
point_chance = 2):
width, height = size
img = Image.new(mode, size, bg_color)
draw = ImageDraw.Draw(img)
if draw_lines:
create_lines(draw,n_line,width,height)
if draw_points:
create_points(draw,point_chance,width,height)
strs = create_strs(draw,chars,length,font_type, font_size,width,height,fg_color)
params = [1 - float(random.randint(1, 2)) / 100,
0,
0,
0,
1 - float(random.randint(1, 10)) / 100,
float(random.randint(1, 2)) / 500,
0.001,
float(random.randint(1, 2)) / 500
]
img = img.transform(size, Image.PERSPECTIVE, params)
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
img.save("/usr/lib/python2.6/site-packages/openstack-dashboard/static/dashboard/img/validate.jpeg")
return strs
The code to create and save the file is inside the function Create_Validate_Code. In your initial version, you never call that function anywhere. Therefore, it never tries to create and save the file, so it never fails.
When you add this:
from .auth_code import Create_Validate_Code
auth_code_str = Create_Validate_Code()
… now you're calling the function. So now it fails. It has nothing whatsoever to do with the third-party module you're using; you could do the same thing with just this:
Create_Validate_Code()
Meanwhile, the reason that creating the file fails is that you don't have write access to directories in the middle of your system's site-packages. This is by design. This is why operating systems have permissions in the first place—to stop some buggy or malicious code run as a normal user from screwing up programs and data needed by the entire system.
Create the file somewhere you do have access to, like some place in your home directory, or the temporary directory, or whatever's appropriate to whatever you're trying to do, and the problem will go away.
Have you tried running the final app as Administrator/root? That usually fixes any "Permission denied" errors while programming.
You shouldn't save data deep within your Python installation. It's really bad practice, which is why the OS is preventing you from doing it. Save the picture somewhere in your home folder.

Problems running code with Python IDLE

I have been attempting to work an iCreate, roomba without a vacuum cleaner attached using Python 2.7.1 and have created working code. When I type each line in by hand it works perfectly, however when putting all the code in together it stalls and does not operate.
import Create
import VideoCapture
from PIL import Image, Imagechops
import os
robot = Create.Create(3)
camera = VideoCapture.Device(0, 1)
(rgb_red, rgb_green, rgb_blue) = (0, 0, 0)
red = Image.open("Red.jpeg")
(redr, redg, redb) = red.getpixel((0, 0))
blue = Image.open("Blue.jpeg")
(bluer, blueg, blueb) = blue.getpixel((0, 0))
green = Image.open("Green.jpeg")
(greenr, greeng, greenb) = green.getpixel((0, 0))
yellow = Image.open("Yellow.jpeg")
(yellowr, yellowg, yellowb) = yellow.getpixel((0, 0))
camera.getImage(0, 0, 'tl')
camera.saveSnapshot('CurrentPicture.jpeg', 0, 0, 'tl')
pic = Image.open("CurrentPicture.jpeg")
(rgb_red, rgb_green, rgb_blue) = pic.getpixel((0, 0))
os.remove("C:\Python27\CurrentPicture.jpeg")
while 0 == 0:
if((rgb_red - redr) < (rgb_green - greeng)) and ((rgb_red - redr) < (rgb_blue - blueb)):
robot.stop()
elif((rgb_blue - blueb) < (rgb_green - greeng)) and ((rgb_blue - blueb) < (rgb_red - redr)):
robot.turn(45, 40)
elif((rgb_green - greeng) < (rgb_red - redr)) and ((rgb_green - greeng) < (rgb_blue - blueb)):
robot.move(50, 50)
camera.saveSnapshot('CurrentPicture.jpeg', 0, 0, 'tl')
pic = Image.open("CurrentPicture.jpeg")
(rgb_red, rgb_green, rgb_blue) = pic.getpixel((0, 0))
os.remove("C:\Python27\CurrentPicture.jpeg")
Are there any issues with IDLE for running multiple lines and just not working, I am not terribly sure what I should be asking. It is just that nothing happens when I run that entire block together but line by line entering works.
-Any help is greatly appreciated.
Instead if pasting the code into IDLE, save it into a file, and run it like this:
python yourfile.py
while 0 == 0: You might want while True: instead.
red = Image.open("Red.jpeg")
(redr, redg, redb) = red.getpixel((0, 0)) is a very complex way of saying RED = (255, 0, 0)

Categories

Resources