How do I get this XWindows.XGetImage call right? - xlib

(update: the XGetPixel problem has been solved thanks to David)
I am practicing some tasks from rosettacode.org for Standard ML, and I am stuck with the XGetImage call from XWindows (PolyML) . I get a badValue error for every attempt in XYPixmap format.
What I did, was
open XWindows ;
val disp = XOpenDisplay "" ;
val win = XCreateSimpleWindow (RootWindow disp) origin (Area {x=0,y=0,w=300,h=100}) 2 0 0xffffff ;
XMapWindow win;
XFlush disp ;
XGetImage win (Area {x=0,y=0,w=100,h=100}) AllPlanes XYPixmap ;
The XGetImage call returns
X Error BadValue in XGetImage
Exception- XWindows "XGetImage failed" raised
The xwindows.cpp source does not make me much wiser:
XImage *image = XGetImage(d,drawable,x,y,w,h,mask,CImageFormat(format));
if (image == 0) RaiseXWindows(taskData, "XGetImage failed");
ZPixmap + XGetPixel work fine in the most recent polyversion, the rest of this post has been solved:
When I try ZPixmap, i get
val im = XGetImage win (Area {x=0,y=0,w=1,h=1}) AllPlanes ZPixmap ;
val im =
XImage
{bitmapBitOrder = MSBFirst, bitmapPad = 32, bitmapUnit = 32,
bitsPerPixel = 1, byteOrder = MSBFirst, bytesPerLine = 4, data =
ImageData
"\^A\^#\^#\^# ... repeat 22 x .... \^A\^#\^#\^#",
depth = 24, format = ZPixmap, size =
Rect {bottom = 1, left = 0, right = 1, top = 0}, ...}
but
XGetPixel disp im (XPoint {x=0,y=0}) ;
crashes PolyML
The XGetImage example (in C) in the Xlib Programming Manual chapter 6.4.2 does not seem to do anything special, just use the display and a visible window. My window win is visible. I also tried the root window, and that does not work either. I think I have followed the PolyML for X manual correctly.
What is missing here ?

It seems there was a bug in the code that implemented XGetPixel in Poly/ML. There is a fix for that now in the github repository. I'm not familiar enough with X-windows to be able to say whether it should work with XYPixmap.

Related

error bad argument #1 to draw (drawable expected, got table), trying to animate a sprite for the main character

new to Lua and love. I'm trying to animate a character for my platform game. I know my key binds and all work but I have never animated before, so I don't even know if I'm going in the right direction or not. I've tried looking up guides so I can compare my code to someone else's but it seems that most of them are outdated. Originally my player was just a white rectangle but now im trying to actually give it a sprite.
Here's my main.lua
local STI = require("sti")
local anim8 = require('anim8')
require("MC")
function love.load()
map1 = STI("map/map1.lua", {"box2d"})
Physics = love.physics.newWorld(0,0)
Physics:setCallbacks(beginContact, endContact)
map1:box2d_init(Physics)
map1.layers.Solid.visible = false
background = love.graphics.newImage("assets/Base pack/bg.png")
mc:load()
end
function love.update(dt)
Physics:update(dt)
mc:update(dt)
end
function love.draw()
love.graphics.push()
love.graphics.scale(5,3)
love.graphics.draw(background)
love.graphics.pop()
map1:draw(0, 0, 2, 2)
love.graphics.push()
love.graphics.scale(2,2)
mc:draw()
love.graphics.pop()
end
function love.keypressed(key)
mc:jump(key)
if keypressed == "escape" then
love.event.quit(0)
end
end
function beginContact(a, b, collision)
mc:beginContact(a, b, collision)
end
function endContact(a, b, collision)
mc:endContact(a, b, collision)
end
I don't believe that there is anything wrong with my main but i think it's necessary to recreate the problem (sorry if it makes this too long). Now my mc.lua is where I'm having the problem since im trying to animate the player themselves by giving them a jump idle and walk animation, I think i will give them a damaged and death animation later.
local anim8 = require('anim8')
mc = {}
spr_mc_walk = love.graphics.newImage("assets/mc sprites/1 Pink_Monster/Pink_Monster_Walk_6.png")
local w = anim8.newGrid(32, 32, spr_mc_walk:getWidth(), spr_mc_walk:getHeight())
walk = anim8.newAnimation(w('1-6', 1), 0.1)
spr_mc_idle = love.graphics.newImage("assets/mc sprites/1 Pink_Monster/Pink_Monster_Idle_4.png")
local i = anim8.newGrid(32, 32, spr_mc_idle:getWidth(), spr_mc_idle:getHeight())
idle = anim8.newAnimation(i('1-4', 1), 0.1)
spr_mc_jump = love.graphics.newImage("assets/mc sprites/1 Pink_Monster/Pink_Monster_Jump_8.png")
local j = anim8.newGrid(32, 32, spr_mc_jump:getWidth(), spr_mc_jump:getHeight())
jump = anim8.newAnimation(j('1-8', 1), 0.1)
obj_mc = walk
function mc:load()
self.x = 100
self.y = 0
self.width = 20
self.height = 60
self.xvel = 0
self.yvel = 0
self.maxspeed = 200
self.acceleration = 4000 -- max speed
self.friction = 3900 -- how long it takes them to reach max speed
self.gravity = 1000
self.jumpAmount = -500
self.grounded = false
self.physics = {}
self.physics.body = love.physics.newBody(Physics, self.x, self.y, "dynamic")
self.physics.body:setFixedRotation(true)
self.physics.shape = love.physics.newRectangleShape(self.width, self.height)
self.physics.fixture = love.physics.newFixture(self.physics.body, self.physics.shape)
end
function mc:draw()
love.graphics.draw(obj_mc, self.x, self.y)
end
This is most of my mc or player function, except for movement and such but this has all the code that I'm confused with. I'm pretty sure I wrote the code right I'm just confused on how to actually implement it now that I have it written down. I thought just doing the draw function would actually draw the idle version of the character but then there's where I get the error. If you need anymore code or anymore details just let me know.
The error that this is happening at is
Error
MC.lua:41: bad argument #1 to 'draw' (Drawable expected, got table)
Traceback
[C]: in function 'draw'
MC.lua:41: in function 'draw'
main.lua:30: in function 'draw'
[C]: in function 'xpcall'
I haven't done any of that for a while, but I believe obj_mc, in this case, is a table of the frames. You need to loop through them during update.
local anim8timer = 0
local anim8index = 1
local anim8rate = 0.2 -- pick an animation rate that looks good for your game
function mc:update( dt )
anim8timer = anim8timer +dt -- add delta time
if anim8timer >= anim8rate then
anim8timer = anim8timer -anim8rate -- reset timer
anim8index = anim8index +1 -- next frame
if anim8index > #obj_mc then anim8index = 1 end -- loop frames
end
end
function mc:draw()
love.graphics.draw( obj_mc[ anim8index ], self.x, self.y )
end
They may have a built-in function that accomplishes some of that, so look for anything that resembles this in the Love2D forum.

Jaspersoft iReports designer 5.6.0; how to fix size of expression editor window

As I am working mainly with large expressions within iReport designer, I want to fix the window size of the expression editor of the iReport designer to a larger size compared with what it defaults to.
Each time I open the expression editor within the iReport designer, it defaults to a relatively small window and then I always have to re-arrange it. As a double click on the title bar doesn't do anything, this is using a considerable amount of time when I have to do this 100ths of time each day.
Is there a way to set the position, width and height of the iReport designer 5.6.0 (I don't use Jaspersoft Studio because of its even more time-consuming file save behavior) so that next time I open the expression editor it will use this position, width and height?
(I have already searched the internet, also here on SO - but nobody seems to have this problem)
As I could nowhere find an answer to this I have quickly developed a workaround with AutoIt.
;Here the AutoIt code:
; *** Variables ***
$FrameInPercent = 10
do
$hWindow = WinWaitActive("[CLASS:SunAwtDialog;TITLE:Expression editor]", "") ; *** Wait here until the Expression editor window is opened ***
WinActivate($hWindow)
; *** Calculate distance from screen edge for Expression editor window ***
$DeskSize = _GetWorkingArea()
$WindowWidth = $DeskSize[2]-($DeskSize[2]*(0.01*2*$FrameInPercent))
$WindowHeight = $DeskSize[3]-($DeskSize[3]*(0.01*2*$FrameInPercent))
$windowStartLeft = ($DeskSize[2]*(0.01*$FrameInPercent))
$windowStartTop = ($DeskSize[3]*(0.01*$FrameInPercent))
WinMove($hWindow, "",$windowStartLeft, $windowStartTop, $WindowWidth, $WindowHeight)
;WinMove($hWindow, "",71, 116, 1815, 863)
Do
Sleep(1000) ; calmly idle around as long as the Expression editor window is open
until NOT(WinExists($hWindow))
until False ; *** Loop forever ***
;===============================================================================
;
; Credits for this function goes to: https://www.autoitscript.com/forum/topic/53788-getting-windows-desktop-size/
; Function Name: _GetWorkingArea()
; Description: Returns the coordinates of desktop working area rectangle
; Parameter(s): None
; Return Value(s): On Success - Array containing coordinates:
; $a[0] = left
; $a[1] = top
; $a[2] = right
; $a[3] = bottom
; On Failure - 0
;
;===============================================================================
Func _GetWorkingArea()
#cs
BOOL WINAPI SystemParametersInfo(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni);
uiAction SPI_GETWORKAREA = 48
#ce
Local $dRECT = DllStructCreate("long; long; long; long")
Local $spiRet = DllCall("User32.dll", "int", "SystemParametersInfo", _
"uint", 48, "uint", 0, "ptr", DllStructGetPtr($dRECT), "uint", 0)
If #error Then Return 0
If $spiRet[0] = 0 Then Return 0
Local $aRet[4] = [DllStructGetData($dRECT, 1), DllStructGetData($dRECT, 2), DllStructGetData($dRECT, 3), DllStructGetData($dRECT, 4)]
Return $aRet
EndFunc
In order to use this you have to install AutoIt: https://www.autoitscript.com/site/autoit/downloads/
And then run this script (doubleclick it). The script will run forever but will not take much CPU power as it is event driven while waiting for the Expression editor to appear and while the expression editor is open, it only scans every 1 second if this window is still open.
Hope this helps someone.
As this is my first AutoIt script, optimizations are welcome :-)

VideoCapture.read() returns past image

I'm running python3.6 with openCV on the Raspberry pi(OS is Raspbian)
The approximate structure of the code is as follows.
The image is captured at time interval(3~5 min).
Captured image is processed in functions and returns measure(kind of accuracy)
Iterate 1.~2. until end_check() returns True
Problem is that the most recent taken image is out of date. It looks it was taken almost 10 minutes ago. All images recently taken are late. But the images taken at the beginning seem to be timed. And the time recorded in all .jpg files entered correctly
+It looks this problem is occured after more than a hour. (20~22 iterates)
Images are captured with cam0.read() in the cv2 package. Below is main part of the code. It is quite long to upload full code. It someone request, I will update.
def run(interval,model_list):
cam0 = cv2.VideoCapture(0) #Only cam0 is used. cam2 is just to record.
camdir = "/home/pi/capstone/cam0/"
cam2 = cv2.VideoCapture(1)
cam2dir = "/home/pi/capstone/cam2/"
runNo = 0
acc_list = list()
error_list = list()
end = False
while(end == False):
print(runNo,"th run")
img_name = "%s.jpg" %runNo
frame, res = cam0.read() #`res` is the image which will be processed
cv2.imwrite(os.path.join(camdir,img_name),res)
_ , cam2pic = cam2.read()
cv2.imwrite(os.path.join(cam2dir,img_name),cam2pic)
try:
temp = Real(res)
mat = temp.match(model_list)
acc_list.append([mat,runNo])
print("Accuracy=", mat)
except ValueError:
acc_list.append(["ValueError",runNo])
error_list.append(["ValueError",runNo])
except AttributeError:
acc_list.append(["AttributeError", runNo])
error_list.append(["AttributeError",runNo])
except SmallObjectError:
acc_list.append(["SmallObjectError", runNo])
error_list.append(["SmallObjectError",runNo])
runNo = runNo+1
endNo = 40
if(runNo/2 > endNo):
end_check(res, end)
elif(runNo > endNo):
end = True
sleep(interval*60)
with open("acc_list.txt", "w") as output: #records for tracking errors
output.write(str(acc_list))
with open("err_list.txt", "w") as output:
output.write(str(error_list))
cam0.release()
cam2.release()
run(3.5,model_list)
(+) Some newly found things and guess
The images time gap is getting bigger with code running
Code finally showed OpenCV Error
It looks kind of Video signal is stored in RAM on R-pi and .read() returning out-dated image in RAM
Stored Video signal in RAM araise resource problem
Below is the OpenCV Error
OpenCV Error: Assertion failed (dsize.area() > 0 || (inv_scale_x > 0 && inv_scale_y > 0)) in resize, file /home/pi/opencv/opencv-3.4.0/modules/imgproc/src/resize.cpp, line 4045
Traceback (most recent call last):
File "runpi.py", line 264, in <module>
run(3.5,model_list)
File "runpi.py", line 234, in run
mat = temp.match(model_list)
File "runpi.py", line 184, in match
self.__resize(model.get_m_inform())
File "runpi.py", line 147, in __resize
self.mask = cv2.resize(self.mask, None, fx=reratio, fy=reratio, interpolation = inter_method)
cv2.error: /home/pi/opencv/opencv-3.4.0/modules/imgproc/src/resize.cpp:4045: error: (-215) dsize.area() > 0 || (inv_scale_x > 0 && inv_scale_y > 0) in function resize
(+) Some part of code araising Error
This is __.resize() method. When I process the image that occured OpenCV Error manually, it works well even if OpenCV Error pointing out kind of image size matter. So I thought it is not matter of image itself or size got from md_inf(). Anyway Here is code.
def __resize(self, md_inf):
#md_inf = [219, 122, 132, 171, 262] <-sample
reratio = md_inf[0]/self.y
if(reratio>1):
inter_method = cv2.INTER_LINEAR
else:
inter_method = cv2.INTER_AREA
###below is line 147###
self.mask = cv2.resize(self.mask, None, fx=reratio, fy=reratio, interpolation = inter_method)
temp = np.zeros((md_inf[3], md_inf[4]), np.uint8)
m_cx, m_cy = md_inf[1:3]
_, contour, _ = cv2.findContours(self.mask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
total_contour = contour[0]
for ctr in contour[1:]:
total_contour = np.concatenate((total_contour, ctr), axis =0)
mmt = cv2.moments(total_contour)
if(mmt['m00'] < 7500):
raise SmallObjectError
self.cy = int(mmt['m10']/mmt['m00']) #y is horrizon axis
self.cx = int(mmt['m01']/mmt['m00']) #x is vertical axis
x, y = self.mask.shape
adjust = m_cx - self.cx + x - temp.shape[0]
if(adjust > 0):
m_cx = m_cx - adjust
temp[(m_cx-self.cx):(m_cx-self.cx) +x, (m_cy-self.cy):(m_cy-self.cy) +y] = self.mask
self.mask = temp
I agree with Mark Serchell's comment. The way I am using is to set variable to time + x seconds and check. OpenCV have useful feature for skiping frames like cam.grab(). It will just read that frame from buffer but will not do anything with it. In that way you can avoid "suffering from buffering". Simple code would be:
import cv2
import time
cam = cv2.VideoCapture(url)
ret,frame = cam.read()
timeCheck = time.time()
future = 10*60 # delay
while ret:
if time.time() >= timeCheck:
ret,frame = cam.read()
# Do your staff here
timeCheck = time.time()+future
else:
# Read from buffer, but skip it
ret = cam.grab() # note that grab() function returnt only status code,not the frame

ggplotly tooltip for geom_text and geom_segment; does not work on Mac

I am working on revising a CRAN package. I have one function call that seems to only cause errors on Mac. It caused an error on r-release-osx-x86_64-mavericks on CRAN. I ran it on El Capitan and Mavericks and it also produced the same error on both of these Mac versions. All other systems checked by CRAN (solaris, linux, windows) did not cause an error.
I created a MWE of the function call as follows (sorry it is long to create the data). Basically, it starts with creating a ggplot2 figure using 3 data frames (edgeDF - all non-path edges, nodeDF - all non-path nodes, pathDF - edges and nodes for path of interest):
set.seed(1)
label=c()
for (i in 1:10){
label[i] = paste(sample(letters,sample(3:10, 1),replace=TRUE),collapse='')
}
nodeDF = data.frame(label = label, x = runif(10,0,10), y = runif(10,0,10))
edgeDF = data.frame()
edgeDF = rbind(edgeDF, c(x=nodeDF[1,]$x, xend=nodeDF[1,]$y, y=nodeDF[2,]$x, yend=nodeDF[2,]$y))
edgeDF = rbind(edgeDF, c(x=nodeDF[5,]$x, xend=nodeDF[5,]$y, y=nodeDF[6,]$x, yend=nodeDF[6,]$y))
colnames(edgeDF) = c("x","y","xend","yend")
r1=runif(1,0,10)
r2=runif(1,0,10)
r3=runif(1,0,10)
r4=runif(1,0,10)
label=c()
for (i in 1:3){
label[i] = paste(sample(letters,sample(3:10, 1),replace=TRUE),collapse='')
}
xend = c(r1, r2, runif(1,0,10))
xstart = c(runif(1,0,10), r1, r2)
yend = c(r3, r4, runif(1,0,10))
ystart = c(runif(1,0,10), r3, r4)
pathDF = data.frame(label=label,xstart=xstart,ystart=ystart,xend=xend,yend=yend,x=xstart,y=ystart)
edgeCol="gray84"
pathEdgeCol="seagreen"
nodeCol="black"
plotTotalImage = ggplot2::ggplot(data = nodeDF, ggplot2::aes(x = x, y = y)) +
ggplot2::geom_segment(data = edgeDF, ggplot2::aes(x=x, y=y, xend=xend, yend=yend), colour = edgeCol) +
ggplot2::geom_segment(data = pathDF, ggplot2::aes(x=xstart, y=ystart, xend=xend, yend=yend), colour = pathEdgeCol) +
ggplot2::geom_text(data = nodeDF, ggplot2::aes(x = x, y = y, label = label), colour = nodeCol)
plotTotalImage = plotTotalImage + ggplot2::geom_text(data = pathDF,ggplot2::aes(x = x, y = y, label = label), fontface= "bold")
I call geom_segment to create the edges (gray ones are off path, green ones are on path). I call geom_text to create node labels (non-bold ones are off path, bold ones are on path). This successfully creates a static image.
At this point, I want to use plotly to add interactivity to the plot. I do not want information to hover for segments; I only want information to hover for node labels. When the mouse hovers over a node label, I want the x value and the label name to be displayed.
The following code works as intended on Windows:
animatePlotTotalImage <- plotly::plotly_build(plotly::ggplotly(plotTotalImage, tooltip = c("x", "label")))
animatePlotTotalImage$data[[1]]$hoverinfo <- "none"
animatePlotTotalImage$data[[2]]$hoverinfo <- "none"
animatePlotTotalImage$data[[3]]$hoverinfo <- c("x+text")
animatePlotTotalImage$data[[4]]$hoverinfo <- c("x+text")
animatePlotTotalImage
However, on Mac, it results in the following Error:
Error in `*tmp*`[[2]] : subscript out of bounds
I am unsure how to go about solving this problem. Any ideas or suggestions would be greatly appreciated!
I might be wrong but I think you have $x missing from your statements:
This works for me (mac Sierra):
animatePlotTotalImage <- plotly::plotly_build(plotly::ggplotly(plotTotalImage, tooltip = c("x", "label")))
animatePlotTotalImage$x$data[[1]]$hoverinfo <- "none"
animatePlotTotalImage$x$data[[2]]$hoverinfo <- "none"
animatePlotTotalImage$x$data[[3]]$hoverinfo <- c("x+text")
animatePlotTotalImage$x$data[[4]]$hoverinfo <- c("x+text")

Corona SDK (Lua) Sprite Sheet Animations

Im trying to get a sprite sheet to run through the 4 images so it plays an animation, although Corona SDK is giving me an error saying
"main.lua40: bad argument #2 to 'newImageSheet' (table (options)expected)
stack traceback: [C]: in function 'newImageSheet' main.lua 40: in main chunk"
exclamationMarkAnimations = graphics.newImageSheet("exclamationMarkAnimated.png", sheetOptions)
exclamationMarkAnimated =
{
width = 12,
height = 12,
numFrames = 4
}
animation = {
{
name = "bobbing",
start = 1,
count = 4,
time = 800,
loopCount = 0, -- "0" means always
loopDirection = "forward"
}
}
exclamationMarkVars = display.newSprite(exclamationMarkAnimations, exclamationMarkAnimated)
exclamationMarkVars:addEventListener("sprite", spriteListener)
Thank you for any and all help.
That project is saved under Corona samples as you can see in the picture below:
and also in this folder: C:\Program Files (x86)\Corona Labs\Corona SDK\Sample Code\Animation
You can use that as the base so save you some time.

Resources