How to call a function into another function with different parameters? - jython

Part 1:
Write function def setPixelToBlack(pixel) to change each pixel's colour to black.
Part2:
Write the function def setPictureToBlack(picture) which blacks out the picture. The function has to call setPixelToBlack from part 1.
I have set up my setPixelToBlack(pixel) code but do not know how to use it within the setPictureToBlack(picture) function!
def setPixelToBlack(pixel):
for p in getPixels(pixel):
value = getRed(p)
setRed(p, value * 0)
value = getGreen(p)
setGreen(p, value * 0)
value = getBlue(p)
setBlue(p, value * 0)
def setPictureToBlack(picture):
for p in getPixels(pixel):
setPixelToBlack(pixel)
> f = pickAFile()
>>p = makePicture(f)
>>>setPictureToBlack(p)
>>>>explore(p), this should black out the image selected!

for p in getPixels(pixel): isn't necessary in setPixelToBlack, as you're not looking at multiple pixels.
You also don't need to get the original value of the pixel if you're just setting it to zero.
I assume the getPixels() function takes in the picture, so change that and setPixelToBlack(p) should get you the desired outcome

Related

Pyqt5 return value in a qtablewidget

im trying to recover a value from a qtablewidget and i have two problems:
First: when i clicked pushbutton i get tablewidget.currentrow but when i change and press another row one, the row printed is not correct.
Second: How can i get the currentrow first column value?
Thanks in advance
def loadtable():
database = DataBase()
cur = database.cursor
cur.execute('select * from sge_job where state like \'r\'')
result = cur.fetchall()
database.close()
ui.tableWidget.setRowCount(0)
header = ui.tableWidget.horizontalHeader()
for i in range(9):
header.setSectionResizeMode(i, QtWidgets.QHeaderView.ResizeToContents)
for row_number, row_data in enumerate(result):
ui.tableWidget.insertRow(row_number)
button = QtWidgets.QPushButton(ui.tableWidget)
button.setText("Clear")
ui.tableWidget.setCellWidget(row_number, 6, button)
button.clicked.connect(printrow)
for colum_number, data in enumerate(row_data):
ui.tableWidget.setItem(row_number, colum_number, QTableWidgetItem(str(data)))
print(row_number, colum_number)
def printrow():
print(ui.tableWidget.currentRow())

compare values in an table in lua

I need help. I am having an table like this:
local dict = {}
dict[1] = {achan = '7f', aseq='02'} --ACK
dict[2] = {dchan = '7f', dseq='03'} --DATA
dict[3] = {achan = '7f', aseq='03'} --ACK
dict[4] = {dchan = '7f', dseq='04'} --DATA
dict[5] = {achan = '7f', aseq='04'} --ACK
dict[6] = {dchan = '7f', dseq='02'} --DATA
Basically I am using this in an Dissector so I don't know the Index except the one I am actually "standing" at the moment.
So what I want to have is:
if the "achan" and the "dchan" is the same and the "aseq" i am standing at the moment is the same as an "dseq" value on positions from the past which are already saved into the table then it should give me back the index from the same "dseq" value from the past.
if (dict[position at the moment].achan == dict[?].dchan) and (dict[position at the moment].aseq == dict[?].dseq) then
return index
end
for example: dchan from position 6 is the same es achan from position 1 and dseq from position 6 is the same as aseq from position 1. So I want to get the position 1 back
You can use a numeric for loop with a negative step size to go back in your table, starting from the previous element. Check wether the achan and aseq fields exist, then compare them vs the dchan and dseq fields of your current entry.
function getPreviousIndex(dict, currentIndex)
for i = currentIndex - 1, 1, -1 do
if dict[i].achan and dict[currentIndex].dchan
and dict[i].achan == dict[currentIndex].dchan
and dict[i].aseq and dict[currentIndex].dseq
and dict[i].aseq == dict[currentIndex].dseq then
return i
end
end
end
This code assumes you have no gaps in your table. You should also add some error handling that makes sure you actually are at a dchan entry and that your index is in range and so on...

Lua OOP grid class with event

I'm learning lua and i'm trying the OOP approach.
To start, I'm trying to make a grid class, but I think i'm still lacking some knowledge to make it do what I want it to do.
This is my code so far:
local screen = require( 'data.screen')
Grid = {}
Grid_mt = { __index = Grid }
--- Constructs a new Grid object.
function Grid:new( params )
local self = {}
local function try( self, event )
print(self.empty)
end
for i = 1, screen.tilesAcross do
if not self[i] then
self[i] = {};
end
for j = 1, screen.tilesDown do
self[i][j] = display.newImageRect( params.group, "images/playable.png", screen.tileWidth, screen.tileHeight )
self[i][j].x = (j - 1) * (screen.tileWidth + screen.tileSpacing) + screen.leftSpacing
self[i][j].y = (i - 1) * (screen.tileHeight + screen.tileSpacing) + screen.topSpacing
self[i][j]._x = i
self[i][j]._y = j
self[i][j].enable = false
self[i][j].empty = true
self[i][j].tap = try
self[i][j]:addEventListener( "tap", self[i][j] )
end
end
setmetatable( self, Grid_mt )
return self
end
function Grid:setEnable(value, x, y)
if value ~= true and value ~= false then
error("Boolean expected")
end
self[x][y].enable = value
end
function Grid:getEnable(x, y)
return self[x][y].enable
end
function Grid:setEmpty(value, x, y)
if value ~= true and value ~= false then
error("Boolean expected")
end
self[x][y].empty = value
end
function Grid:getEmpty(x, y)
return self[x][y].empty
end
function Grid:SetmColor()
self[1][4]:setFillColor( 255,255 )
end
I have 2 questions:
My event works but I would like to do something like: print(self:getEmpty() )
but whenever I try to use a method in my event, it doesn't work "attempt to call method 'getEmpty' (a nil value)"
and also the setfillcolor wwon't work, I want to be able to change the color of a case with it.
Thanks for your time!
and if i'm going to the wrong road, let me know, and by the way, I have a working code without make a class, this is just for training purpose :)
Thnaks!
The issue is that self[i][j] is not a Grid, only self is a Grid. So when the event handler is called, self in the handler is the display object, not the Grid object. If the handler needs to know the grid object, you could assign the grid to each display object:
self[i][j].grid = self
then in try you could do
grid = self.grid
But in this case you may get a cleaner design if you have the tap handler not be specific to each display object. In this case you would use an upvalue, you can just use self:
function Grid:new( params )
local self = {}
local function try( event ) -- omit the first param, self is an upvalue
print(self.empty)
end
for i = 1, screen.tilesAcross do
...
for j = 1, screen.tilesDown do
self[i][j] = display.newImageRect( ... )
...
self[i][j]:addEventListener( "tap", try )
end
end
Since listener given is a function rather than a table, it gets only one parameter, the event, and self is an upvalue so it will be the Grid instance created just above the try function.
For the first question, more information would be needed. See my comment above.
As for the setFillColor not working, the following is taken from the Corona docs:
object:setFillColor( gray )
object:setFillColor( gray, alpha )
object:setFillColor( red, green, blue )
object:setFillColor( red, green, blue, alpha )
object:setFillColor( gradient )
gray, red, green, blue, alpha (optional)
Numbers between 0 and 1 that represent the corresponding
value for that channel. alpha represents the opacity of the object.
Now, when you are trying to execute:
self[1][4]:setFillColor( 255,255 )
you are passing the values for gray and alpha channels. The values NEED TO BE less than, or equal to 1. Probably you want to pass 1 (as 255 is generally the max. value)

Matlab's arrayfun for uniform output of class objects

I need to build an array of objects of class ID using arrayfun:
% ID.m
classdef ID < handle
properties
id
end
methods
function obj = ID(id)
obj.id = id;
end
end
end
But get an error:
>> ids = 1:5;
>> s = arrayfun(#(id) ID(id), ids)
??? Error using ==> arrayfun
ID output type is not currently implemented.
I can build it alternatively in a loop:
s = [];
for k = 1 : length(ids)
s = cat(1, s, ID(ids(k)));
end
but what is wrong with this usage of arrayfun?
Edit (clarification of the question): The question is not how to workaround the problem (there are several solutions), but why the simple syntax s = arrayfun(#(id) ID(id), ids); doesn't work. Thanks.
Perhaps the easiest is to use cellfun, or force arrayfun to return a cell array by setting the 'UniformOutput' option. Then you can convert this cell array to an array of obects (same as using cat above).
s = arrayfun(#(x) ID(x), ids, 'UniformOutput', false);
s = [s{:}];
You are asking arrayfun to do something it isn't built to do.
The output from arrayfun must be:
scalar values (numeric, logical, character, or structure) or cell
arrays.
Objects don't count as any of the scalar types, which is why the "workarounds" all involve using a cell array as the output. One thing to try is using cell2mat to convert the output to your desired form; it can be done in one line. (I haven't tested it though.)
s = cell2mat(arrayfun(#(id) ID(id), ids,'UniformOutput',false));
This is how I would create an array of objects:
s = ID.empty(0,5);
for i=5:-1:1
s(i) = ID(i);
end
It is always a good idea to provide a "default constructor" with no arguments, or at least use default values:
classdef ID < handle
properties
id
end
methods
function obj = ID(id)
if nargin<1, id = 0; end
obj.id = id;
end
end
end

Why is MATLAB reporting my variable uninitialized?

I made a class and in one of its methods I needed to calculate the distance between two points. So I wrote an ordinary function named "remoteness" to do this for me.
Compilation Error:
At compilation, "remoteness" was
determined to be a variable and this
variable is uninitialized.
"remoteness" is also a function name
and previous versions of MATLAB would
have called the function.
However, MATLAB 7 forbids the use of the same name in the same context as both a function and a variable.
Error in ==> TRobot>TRobot.makeVisibilityGraph at 58
obj.visiblityGraph(k,k+1) = remoteness(:,obj.VGVertices(k),obj.VGVertices(:,k+1));
I thought the name remoteness might be a name of another function, but when I changed its name to kamran the error persisted. It should be noted that I can use the kamran function (or remoteness) in the command line without any problem.
Command line example:
>> kamran([0,0],[3,4])
ans = 5
The code of the kamran function is in a separate m file.
Code for kamran function:
function dist = kamran(v1,v2)
dist = sqrt( (v1(1) - v2(1)) ^2 + (v1(2) - v2(2)) ^2 );
Code example for how kamran function is used:
function obj = makeVisibilityGraph(obj)
verticesNumber = 0;
for num = 1: size(obj.staticObstacle,2)
verticesNumber = verticesNumber + size(obj.staticObstacle(num).polygon,2);
end
% in the below line, 2 is for start and goal vertices
obj.visibilityGraph = ones(2 + size(obj.VGVertices,2)) * Inf;
for j=1 : size(obj.staticObstacle,2)
index = size(obj.VGVertices,2);
obj.VGVertices = [obj.VGVertices, obj.staticObstacle(j).polygon];
obj.labelVGVertices = [obj.labelVGVertices, ones(1,size(obj.staticObstacle(j).polygon,2))* j ];
for k = index+1 : (size(obj.VGVertices,2)-1)
obj.visiblityGraph(k,k+1) = kamran(:,obj.VGVertices(k),obj.VGVertices(:,k+1));
end
% as the first and last point of a polygon are visible to each
% other, so set them visible to each other
obj.visibilityGraph(index+1,size(obj.VGVertices,2)) = ...
kamran( obj.VGVertices(:,index+1), obj.VGVertices(:,size(obj.VGVertices,2)));
end
end
You seem to be trying to use kamran as an array:
kamran(:,obj.VGVertices(k),obj.VGVertices(:,k+1));
Notice the first parameter ":"?
I would bet MATLAB assumes that kamran (as called here) should be a 3-dimensional array, and you are trying to select the subset containing
kamran(all-of-first-index, Nth-of-second, Mth-of-third)
The second invocation of kamran looks right:
kamran( obj.VGVertices(:,index+1), obj.VGVertices(:,size(obj.VGVertices,2))
I do not know MATLAB but I notice on this line, you are running kamran with what looks like 3 arguments. In all other cases, it is executed with 2 arguments. Maybe there is something to that?
kamran(:,obj.VGVertices(k),obj.VGVertices(:,k+1));