lua:90: attempt to index field '?' (a nil value) - multidimensional-array

I cannot get my 2 dimensional variable to be recognized correctly when I call it. When I print it, it seems to work fine, but when I attempt to call it from within a function it goes bananas on me.
Here is my code:
math.randomseed(os.time())
math.random(); math.random(); math.random()
--init
local t = ""
--t == type
local year = 2014
--year is placeholder with no real value.
local i = 1
local x = 0
local y = 0
local z = 0
local o = 0
--
local l = 0
local l1 = 0
local l2 = 0
--
local h = 1
--Junk Variables
local month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}
local days = {0, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
--Days linked to months, weeks come as calculated
local m = 1
--"m" is the real month value to be used within the code as the literal value.
fd = {} -- create the matrix
for y=1,5 do
fd[y] = {} -- create a new row
for z=1,5 do
fd[y][z] = 0
end
end
--fd = Family/Day
na = {1, 2, 3, 4 ,5}
--numbers not allocated for the day
fv = {}
--[12][days[m]][5]
--final value to be printed literally into string of txt file.
local s = ""
--string variable
io.write("Please enter a month (ONLY USE NUMBERS)")
io.flush()
m=io.read()
io.write("Please enter a chore creation type (daily, weekly, monthly [Case sensitive])")
t=io.read()
--
m = tonumber(m)
--
for y=1,12 do
fv[y] = {}
for z=1,days[m] do
fv[y][z] = {}
for o=1,5 do
fv[y][z][o] = 0
end
end
end
--
if t == "daily" then
local f,err = io.open("ChoreDaily.txt","w")
if not f then return print(err) end
f:write("")
--
repeat
i = 0
y = 0
print(">>")
repeat
if h <= days[m] then
--
repeat
if h <= days[m] then
--
os.execute("cls")
l1 = math.random(1,2)
l2 = math.random(3,4)
l = math.random(l1,l2)
repeat
o = math.random(1,5)
l = l-1
until l == 0
--
if y == 0 then
--
if na[o] > 0 then
if x < 4 then
s = s .. tostring(na[o]) .. ", "
elseif x >= 4 then
s = s .. tostring(na[o])
end
fd[x][y] = na[o] -- this is the problem.
na[o] = 0
x = x+1
print("!")
end
--
I think it's pretty obvious what I am attempting to make overall, but it's a chore list creator. pretty primitive and I was hoping I could do it all myself, but unfortunately if I can't utilize 2 dimensional variables I'm not going to be able to go much further.
There are some unused variables and whatnot hanging around. I plan to get rid of those later.

x is initialized as 0, and is not changed before you try to access fd[x][y]. But the valid index of the table fd is from 1 to 5, which means fd[x] is nil here, you can't access fd[x][y].

Related

"RecursionError: maximum recursion depth exceeded" while adding a new constraints to a convex problem in cvxpy

I'm new in cvxpy and working on a certain energy optimization model I'm trying to add new constraints. When I try to append the new constraints i get the following error "RecursionError: maximum recursion depth exceeded". If I exclude the last lines related (rules.appen(...)) everything works. I have tried to increase the system recursion limit but this doesn't work. Any suggestion?
class ProductionRamping(Constraint):
# it runs on both operation and planning, single- and multi-region
def __get_energy_prod_differences(self):
"""Creates variables to constrain the increase and decrease
in energy production when passing from one timestep to the next"""
# Create a dataframe containing the differences between the energy production of each tech
# in each timestep and the production in the previous timestep
energy_prod_differences = {}
# for each region
for reg in self.model_data.settings.regions:
energy_prod_differences_regional = {}
#for each tech, except demand, transmission, and storage
for tech_type in self.model_data.settings.technologies[reg].keys():
if tech_type == "Demand" or tech_type == "Transmission" or tech_type == "Storage":
continue
# select the first row
first_row = cp.reshape(
self.variables.technology_prod[reg][tech_type][0,:],
(1, self.variables.technology_prod[reg][tech_type][0,:].shape[0])
)
# in the case the timesteps are just one, the shifted dataframe containing the energy production
# will only be the first row; if timesteps are > 1 instead we have a shifted dataframe
if self.variables.technology_prod[reg][tech_type].shape[0] > 1:
shifted_prod = cp.vstack([first_row, (self.variables.technology_prod[reg][tech_type][:-1,:])])
else:
shifted_prod = first_row
# compute the difference between the energy production in each timestep and the the production in the previouos timestep
energy_prod_differences_regional[tech_type] = self.variables.technology_prod[reg][tech_type] - shifted_prod
energy_prod_differences[reg] = energy_prod_differences_regional
return energy_prod_differences ## 8760*nyears x ntechs
def transform_total_capacity(capacity, regions, timeslice_fraction, years):
totcapacity ={}
for reg in regions:
totcapacity_regional = {}
for tech_type in capacity[reg].keys():
if tech_type == "Demand" or tech_type == "Transmission" or tech_type == "Storage":
continue
totcapacity_hourly = cp.reshape(
capacity[reg][tech_type][0,:],
(1, capacity[reg][tech_type][0,:].shape[0]))
totcapacity_yearly = totcapacity_hourly
for hours in np.arange(len(timeslice_fraction)-1):
totcapacity_yearly = cp.vstack([totcapacity_yearly,totcapacity_hourly])
totcapacity_multiyear_regional = totcapacity_yearly
for indx in np.arange(len(years)-1):
totcapacity_hourly1 = cp.reshape(
capacity[reg][tech_type][indx,:],
(1, capacity[reg][tech_type][indx,:].shape[0]))
totcapacity_yearly1 = totcapacity_hourly1
for hours in np.arange(len(timeslice_fraction)-1):
totcapacity_yearly1 = cp.vstack([totcapacity_yearly1,totcapacity_hourly1])
totcapacity_multiyear_regional = cp.vstack ([totcapacity_multiyear_regional,totcapacity_yearly1])
totcapacity_regional[tech_type] = totcapacity_multiyear_regional
totcapacity[reg] = totcapacity_regional
return totcapacity
def _check(self):
assert hasattr(self.variables, 'totalcapacity'), "totalcapacity must be defined"
def rules(self):
rules = []
totcapacity = transform_total_capacity(
self.variables.totalcapacity,
self.model_data.settings.regions,
self.model_data.settings.timeslice_fraction,
self.model_data.settings.years)
for reg in self.model_data.settings.regions:
for tech_type, value in totcapacity[reg].items():
max_percentage_ramps = self.model_data.regional_parameters[reg]["prod_max_ramp"].loc[:, tech_type]
max_percentage_ramps = max_percentage_ramps.reindex(max_percentage_ramps.index.repeat(
len(self.model_data.settings.timeslice_fraction))
).values
min_percentage_ramps = self.model_data.regional_parameters[reg]["prod_min_ramp"].loc[:, tech_type]
min_percentage_ramps = min_percentage_ramps.reindex(min_percentage_ramps.index.repeat(
len(self.model_data.settings.timeslice_fraction))
).values
energy_prod_differences = self.__get_energy_prod_differences()
for indx, year in enumerate(self.model_data.settings.years):
max_ramp_in_timestep = cp.multiply ( value [indx * len(self.model_data.settings.timeslice_fraction) : (indx + 1)
* len(self.model_data.settings.time_steps), :] , max_percentage_ramps)
min_ramp_in_timestep = cp.multiply ( value [indx * len(self.model_data.settings.timeslice_fraction) : (indx + 1)
* len(self.model_data.settings.time_steps), :] , min_percentage_ramps)
energy_prod = energy_prod_differences[reg][tech_type][indx * len(self.model_data.settings.timeslice_fraction) : (indx + 1)
* len(self.model_data.settings.timeslice_fraction), :]
diff = energy_prod - max_ramp_in_timestep
diff1 = energy_prod * -1 - min_ramp_in_timestep
rules.append(
diff <= 0
)
rules.append(
diff1 <= 0
)
return rules

Weighted average cost of short-term stock trading

I'm new to programming and trying to learn Julia. I tried to compute the weighted average cost of short-term stock trading activities as I did before in R. I rewrite the code in Julia, unfortunately, it return the incorrect result in data frame format.
I tried to investigate the result of each iteration step by changing return vwavg to println([volume[i], s, unitprice[i], value[i], t, vwavg[i], u]) and the output is correct. is it a problem with rounding?
Really appreciate your help
# create trial dataset
df = DataFrame(qty = [3, 2, 2, -7, 4, 4, -3,-2, 4, 4, -2, -3],
price = [100.0, 99.0, 101.0, 103.0, 95.0, 93.0, 90.0, 90.0, 93.0, 95.0, 93.0, 92.0])
# create function for weighted average cost of stock price
function vwacost(volume, unitprice)
value = Vector{Float64}(undef, length(volume))
vwavg = Vector{Float64}(undef, length(volume))
for i in 1:length(volume)
s = 0
t = 0
u = 0
if volume[i]>0
value[i] = (volume[i]*unitprice[i]) + t
volume[i] = volume[i] + s
vwavg[i] = value[i]/volume[i]
u = vwavg[i]
s = volume[i]
t = value[i]
else
volume[i] = volume[i] + s
value[i] = u * volume[i]
s = volume[i]
t = value[i]
vwavg[i] = u
end
return vwavg
end
end
out = transform(df, [:qty, :price] => vwacost)
Simple error:
for i in 1:length(volume)
...
return vwavg
end
should be:
for i in 1:length(volume)
...
end
return vwavg
You are currently returning the result after the first loop iteration, which is why your resulting vwawg vector has only one (the first) calculated entry, with all other entries being zero/whatever was in memory when you created the vwawg vector in the first place.
Ok, the second problem of changing original df that result in incorrect result can be solved by copy(df):
out = select(copy(df), [:qty, :price] => vwacost => :avgcost)
thus, the original df will not change and the result will consistent over time.

Push dictionary? How to achieve this in Lua?

Say I have this dictionary in Lua
places = {dest1 = 10, dest2 = 20, dest3 = 30}
In my program I check if the dictionary has met my size limit in this case 3, how do I push the oldest key/value pair out of the dictionary and add a new one?
places["newdest"] = 50
--places should now look like this, dest3 pushed off and newdest added and dictionary has kept its size
places = {newdest = 50, dest1 = 10, dest2 = 20}
It's not too difficult to do this, if you really needed it, and it's easily reusable as well.
local function ld_next(t, i) -- This is an ordered iterator, oldest first.
if i <= #t then
return i + 1, t[i], t[t[i]]
end
end
local limited_dict = {__newindex = function(t,k,v)
if #t == t[0] then -- Pop the last entry.
t[table.remove(t, 1)] = nil
end
table.insert(t, k)
rawset(t, k, v)
end, __pairs = function(t)
return ld_next, t, 1
end}
local t = setmetatable({[0] = 3}, limited_dict)
t['dest1'] = 10
t['dest2'] = 20
t['dest3'] = 30
t['dest4'] = 50
for i, k, v in pairs(t) do print(k, v) end
dest2 20
dest3 30
dest4 50
The order is stored in the numeric indices, with the 0th index indicating the limit of unique keys that the table can have.
Given that dictionary keys do not save their entered position, I wrote something that should be able to help you accomplish what you want, regardless.
function push_old(t, k, v)
local z = fifo[1]
t[z] = nil
t[k] = v
table.insert(fifo, k)
table.remove(fifo, 1)
end
You would need to create the fifo table first, based on the order you entered the keys (for instance, fifo = {"dest3", "dest2", "dest1"}, based on your post, from first entered to last entered), then use:
push_old(places, "newdest", 50)
and the function will do the work. Happy holidays!

Length of nested array lua

I am having trouble figuring out how to get the length of a matrix within a matrix within a matrix (nested depth of 3). So what the code is doing in short is... looks to see if the publisher is already in the array, then it either adds a new column in the array with a new publisher and the corresponding system, or adds the new system to the existing array publisher
output[k][1] is the publisher array
output[k][2][l] is the system
where the first [] is the amount of different publishers
and the second [] is the amount of different systems within the same publisher
So how would I find out what the length of the third deep array is?
function reviewPubCount()
local output = {}
local k = 0
for i = 1, #keys do
if string.find(tostring(keys[i]), '_') then
key = Split(tostring(keys[i]), '_')
for j = 1, #reviewer_code do
if key[1] == reviewer_code[j] and key[1] ~= '' then
k = k + 1
output[k] = {}
-- output[k] = reviewer_code[j]
for l = 1, k do
if output[l][1] == reviewer_code[j] then
ltable = output[l][2]
temp = table.getn(ltable)
output[l][2][temp+1] = key[2]
else
output[k][1] = reviewer_code[j]
output[k][2][1] = key[2]
end
end
end
end
end
end
return output
end
The code has been fixed here for future reference: http://codepad.org/3di3BOD2#output
You should be able to replace table.getn(t) with #t (it's deprecated in Lua 5.1 and removed in Lua 5.2); instead of this:
ltable = output[l][2]
temp = table.getn(ltable)
output[l][2][temp+1] = key[2]
try this:
output[l][2][#output[l][2]+1] = key[2]
or this:
table.insert(output[l][2], key[2])

Can Do While Loop stop when counter reaches X

I want to edit some legacy code written in classic-ASP.
Currently I've got a subroutine declared that uses a for-next loop to output some radio buttons:
For i = 1 to Cols
response.write "blah"
...
Next
i is simply a counter, Cols is a value passed to the sub-routine. I tried editing the for-loop to be a while loop instead:
i = Start
do while i <= Cols
response.write "blah"
...
i = i + 1
loop
But I get a Response Buffer Limit Exceeded error. If I replace Cols with the value it works fine. Is this a limitation in classic-ASP?
Reason I want to use a do while loop is because currently the sub-routine is limited to looping from 1 to Cols. It would be helpful to sometimes specify the loop counts backwards (i.e. step -1) but I can't write:
if Direction = Backwards then
For i = Cols to 1 step -1
else
For i = 1 to Cols
end if
How about:
If Direction = Backwards Then
cs = 10
ce = 1
s = -1
Else
cs = 1
ce = 10
s = 1
End If
For i = cs To ce Step s
''
Next

Resources