How to create an array of pointers to objects in Matlab? - arrays

I'm writing a Matlab script where I have a bunch of objects of a same self defined class, say A, B and C. Then I have a function that work on any of the 2 objects, like func(A,B).
Now I want to pick an object, say A, and then func(A,x) through all the other objects. So basically achieve something like:
func(A,B)
func(A,C)
A.update()
func(B,A)
func(B,C)
B.update()
...
So I need to create an array of all the objects I can loop through, while excluding itself of course. I tried to do it with cell array, so I have:
AllObjs = {A,B,C}
for i=1:length(AllObjs)
if ~isequal(A, AllObjs{i})
func(A, AllObjs{i})
end
end
A.update()
However, when A is updated, the A in AllObjs doesn't get updates. So for the next loop I have to create a new array of all the objects. It's doable in this simple example but not manageable when the objects get updated elsewhere. So I would like to have an array of pointers to all the objects. My Google search tells me there's no pointer in Matlab, but is there a way to achieve what I want to do here?

I suspect (its difficult without seeing your code) your classes A, B & C do not inherit from from handle.
Take the examples below:
classdef noHandle
properties
name = '';
end
methods
function obj = noHandle ( name )
obj.name = name;
end
end
end
A = noHandle ( 'A' );
B = noHandle ( 'B' );
C = noHandle ( 'C' );
allObjs = { A B C }
allObjs{1}.name % check its name is "A"
% change the name of A
A.name = 'AAA'
allObjs{1}.name % see that allObjs{1} is still A.
However if you do:
classdef fromHandle < handle
properties
name = '';
end
methods
function obj = fromHandle ( name )
obj.name = name;
end
end
end
Then do:
A = fromHandle ( 'A' );
B = fromHandle ( 'B' );
C = fromHandle ( 'C' );
allObjs = { A B C }
allObjs{1}.name % check its name is "A"
% change the name of A
A.name = 'AAA'
allObjs{1}.name % see that allObjs{1} is updated to AAA.

Related

Copying a tables values in Lua is changing the originals value

I want to copy a simple table however whenever I change the copied table it changes the original table too and it's very bizarre
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
board = {}
print("board: "..tablelength(board))
newBoard = board
newBoard[tablelength(newBoard) + 1] = 1
print("board: "..tablelength(board))
newBoard[tablelength(newBoard) + 1] = 1
print("board: "..tablelength(board))
Output:
board: 0
board: 1
board: 2
newBoard = board only created a new reference newBoard, second after board, to the same table, which was creared by {}.
You need to deep copy a table, if you want a new one.
Something like this:
local function deep_copy( tbl )
local copy = {}
for key, value in pairs( tbl ) do
if type( value ) ~= 'table' then
copy[key] = value
else
copy[key] = deep_copy( value )
end
end
return copy
end
This is a naïve implementation that does not copy metatables and keys that are tables (it's possible in Lua), and tables that include references to themselves, but it's likely to be enough for your purposes.
Further reading: https://www.lua.org/pil/2.5.html, starting from paragraph two.
P.S. A less naïve implementation, based on http://lua-users.org/wiki/CopyTable:
local function deep_copy( original, copies )
if type( original ) ~= 'table' then return original end
-- original is a table.
copies = copies or {} -- this is a cache of already copied tables.
-- This table has been copied previously.
if copies[original] then return copies[original] end
-- We need to deep copy the table not deep copied previously.
local copy = {}
copies[original] = copy -- store a reference to copied table in the cache.
for key, value in pairs( original ) do
local dc_key, dc_value = deep_copy( key, copies ), deep_copy( value, copies )
copy[dc_key] = dc_value
end
setmetatable(copy, deep_copy( getmetatable( original ), copies) )
return copy
end

Anorm SQL Folding a List into a class result

please pardon the level of detail. I'm not completely sure how to phrase this question.
I am new to scala and still learning the intricacies of the language. I have a project where all the data I need is contained in a table with a layout like this:
CREATE TABLE demo_data ( table_key varchar(10), description varchar(40), data_key varchar(10), data_value varchar(10) );
Where the table_key column contains the main key I'm searching on, and the description repeats for every row with that table_key. In addition there are descriptive keys and values contained in the data_key and data_value pairs.
I need to consolidate a set of these data_keys into my resulting class so that the class will end up like this:
case class Tab ( tableKey: String, description: String, valA: String, valB: String, valC: String )
object Tab {
val simple = {
get[String]("table_key") ~
get[String]("description") ~
get[String]("val_a") ~
get[String]("val_b") ~
get[String]("val_c") map {
case tableKey ~ description ~ valA ~ valB ~ valC => Tab(table_key, description, valA, valB, valC)
}
}
def list(tabKey: String) : List[Tab] = {
DB.withConnection { implicit connection =>
val tabs = SQL(
"""
SELECT DISTINCT p.table_key, p.description,
a.data_value val_a,
b.data_value val_b,
c.data_value val_c
FROM demo_data p
JOIN demo_data a on p.table_key = a.table_key and a.data_key = 'A'
JOIN demo_data b on p.table_key = b.table_key and b.data_key = 'B'
JOIN demo_data c on p.table_key = c.table_key and c.data_key = 'C'
WHERE p.table_key = {tabKey}
"""
).on('tabKey -> tabKey).as(Tab.simple *)
}
return tabs
}
}
which will return what I want, however I have more than 30 data keys that I wish to retrieve in this manner, and the joins to itself rapidly becomes unmanageable. As in the query ran for 1.5 hours and used up 20GB worth of temporary tablespace before running out of disk space.
So instead I am doing a separate class that retrieves a list of data keys and data values for a given table key using the "where data_key in ('A','B','C',...)", and now I'd like to "flatten" the returned list into a resulting object that will have the valA, valB, valC, ... in it. I still want to return a list of the flattened objects to the calling routine.
Let me try to idealize what I'd like to accomplish..
Take a header result set and a detail result set, extract out the keys out of the detail result set to populate additional elements/properties in the header result set and produce a list of classes containing the all the elements of the header result set, and the selected properties from the detail result set. So I get a list of TabHeader(tabKey,Desc) and for each I retrieve a list of interesting TabDetail(DataKey,DataValue), I then extract out the element where the DataKey == 'A' and put the DataValue element in Tab(valA), and do the same for DataKey == 'B', 'C', ... After I'm done I wish to produce a Tab(tabKey, Desc, valA, valB, valC, ...) in place of the corresponding TabHeader. I could quite possibly muddle through this in Java, but I'm treating this as a learning opportunity and would like to know a good way to do this in Scala.
I'm feeling that something with the scala mapping should do what I need, but I haven't been able to track down exactly what.

Save check constraint values to variables

I get a table check constraint definition this way:
select a.CHECK_CLAUSE
from INFORMATION_SCHEMA.CHECK_CONSTRAINTS a,INFORMATION_SCHEMA.TABLE_CONSTRAINTS b
where b.TABLE_NAME = 'table name'
For my example, suppose running this query returns this:
[([depname]='mathematics' OR [depname]='electronics' OR [depname]='computer science')]
How do I assign the values ​​specified in the check constraint into variables? i.e. computer science, mathematics and electronics?
It looks like you're getting a string returned. What you can do is split the string on instances of OR and store that in an array, and then run through the array and split each element on = to isolate the values. So, if you were to do this in PHP, the code might look something like this:
// For reasons of simplicity we will assume the result is stored in $result,
// and the leading [( and trailing )] have already been removed
$values = array();
$resultsplit = explode(' OR ', $result);
/* $resultsplit is now an array:
* $resultsplit[0] = "[depname]='mathematics'"
* $resultsplit[1] = "[depname]='electronics'"
* $resultsplit[2] = "[depname]='computer science'"
*/
if ($result != '') {
foreach ($resultsplit as $rs) {
$rsparts = explode('=', $rs);
/* $rsparts is now an array. On the first element:
* $rsparts[0] = "[depname]"
* $rsparts[1] = "'mathematics'"
* So all we need to do is stick $rsparts[1] into $values
*/
$values[] = $rsparts[1];
}
}
This will put all of the values into the array $values (including the single-quotes at the beginning and end) for you to do with as you please, regardless of how many there are. If PHP is not the language you have available to you, the same method should still work in your language of choice.

Lua - check if array exists

I'm trying to find out if a certain array exists via an if statement such as
if array{} == nil then array = {} else print("it exists") end
The above doesn't work it seems and I have no way of checking if it exists, basically I'm creating an AddOn which scans a log for a certain event and if it's true it returns the spellName. I wish to create an array with that spellName, however spellName = {} doesn't work as it seems to just create a new array (rather than updating the existing one).
local _SPD = CreateFrame("Frame");
_SPD:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED");
_SPD:SetScript("OnEvent", function(self, event, ...)
local timestamp, type, sourceName = select(1, ...), select(2, ...), select(5, ...)
if (event == "COMBAT_LOG_EVENT_UNFILTERED") then
if select(2,...) == "SPELL_AURA_APPLIED" then
if select(5,...) == UnitName("player") then
local spellID, spellName = select(12, ...), select(13, ...)
spellName = {
sourceName = {
}
}
table.insert(spellName["sourceName"], {id = spellID, stamp = timestamp })
for k,v in pairs ( spellName["sourceName"] ) do
print (k.. ": " ..v["id"].. " at " ..v["stamp"])
end
end
end
end
end);
Basically it's just re-creating the table every time a certain aura is applied on me (which is expected behavior)
I've banged my head but I have no idea how to check if spellName (and sourceName) exists and if so do not create them again since in this case the variable already exists because it returns the value to me so I can't check if they're nil as they won't be, I need to somehow check if a table exists on those values and if not create them.
Thanks in advance.
Your declaration for table checking is wrong. Use it like this:
if type(array) == "table" then
print("it exists")
else
array = {}
end
Try this:
local spellID, spellName = select(12, ...), select(13, ...)
spellName = spellName or {}
spellName.sourceName = spellName.sourceName or {}
table.insert(spellName.sourceName, {id = spellID, stamp = timestamp })

Django Field Choices

Given below is my Model definition and I have added this module part of the Admin. I'm trying to create new row and while selecting value '3' or any other value for Duration field(listed as select fields), I get the following error.- "Value 3 is not a valid choice".
Please provide your inputs.
Model Definition
NO_OF_HRS = (
('1','One'),
('2','Two'),
('3','Three'),
('4','Four'),
('5','Five'),
('6','Six'),
('7','Seven'),
('8','Eight'),
('9','Nine'),
('10','Ten'),
('11','Eleven'),
('12','Twelve'),
)
YR_MONTH = (
("Y", "Year"),
("M", "Month"),
)
POS_STATUS = (
("A", "Active"),
("C", "Closed"),
)
datecreated = models.DateTimeField()
volposition = models.CharField(max_length=300)
roledesc = models.CharField(max_length=5000)
noofhours = models.IntegerField(blank = True,null = True)
Qualreqt = models.CharField(max_length=8000)
Duration = models.IntegerField(choices=NO_OF_HRS,blank = True,null = True)
Durationyrmon = models.CharField(choices=YR_MONTH,max_length=10)
posstatus = models.CharField(choices=POS_STATUS,max_length=1)
teamrelation = models.CharField(max_length=50)
When you use choices, the first value of the tuple is the value that will be stored in the database and the second value is the value that will be shown in the admin.
In NO_OF_HRS the values are strings (for example '1', '2') but it is a models.IntegerField so the values should be integers. That's why you're now getting an error.
Opened a ticket on django with fix and dirty fix:
https://code.djangoproject.com/ticket/24897

Resources