function takes for example rsi and from declared for me historical bar 1 to 12 finds me maximum value ( integer or '00,0') of rsi.
//#version=5
indicator("loop", shorttitle="loop")
len = input.int(14, title="RSI Length")
src = input.source(close, "RSI Source")
Rsi = ta.rsi(src, len)
plot(Rsi*10, "RSI", color=#673ed8)
hline(65,linestyle= hline.style_dashed , color=color.new(color.red, 0))
minF = 1, maxF = 12, RsiFunction = Rsi
ff_loopMax(RsiFunction,minF, maxF) =>
var float Max = na
var float MaxOdpCena = na
var int MaxNrBar = na
for i=minF to maxF
if i == minF
Max := RsiFunction[i]
//MaxOdpCena := high[i]
//MaxNrBar := i
else
//MaxOdpCena := Max > RsiFunction[i] ? MaxOdpCena : high[i]
//MaxNrBar := Max > RsiFunction[i] ? MaxNrBar : i
Max := math.max(Max,RsiFunction[i])
// I want Max result from function
plot(Max, "rsiMax", color=#b63253)
Result = ff_loopMax(Rsi,5,15)
The code extracted from function should work alone. But I can't cope with function.
A function in pine script return the value of the last expression. In your case, the last expression is Max, but you can't access this directly. You call the function, and set this return to a variable.
You should change the last two lines to:
Result = ff_loopMax(Rsi,5,15) // Result is now equal to Max
plot(Result, "rsiMax", color=#b63253)
I have a function that converts a decimal value to binary. I understand I have the logic correct as I can get it to work outside of a function.
def decimaltobinary(value):
invertedbinary = []
value = int(value)
while value >= 1:
value = (value / 2)
invertedbinary.append(value)
value = int(value)
for n, i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n] = 0
else:
invertedbinary[n] = 1
invertedbinary.reverse()
value = ''.join(str(e) for e in invertedbinary)
return value
decimaltobinary(firstvalue)
print (firstvalue)
decimaltobinary(secondvalue)
print (secondvalue)
Let's say firstvalue = 5 and secondvalue = 10. The values returned each time the function is executed should be 101 and 1010 respectively. However, the values I get printed are the starting values of five and ten. Why is this happening?
The code works as expected, but you didn't assign the returned value:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
Note that there are easier ways to accomplish your goal:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'
I have a problem, can you help me.
var query = (from MONHOC in db.tbl_MONHOCs
where
(MONHOC.IS_DELETE != 1 ||
MONHOC.IS_DELETE == null) &&
MONHOC.ISBATBUOC == 1
select new
{
ID = ("MH_CHA_" + Convert.ToString(MONHOC.ID_MONHOC)),
ID_NAME = MONHOC.ID_MONHOC,
MA_MONHOC = MONHOC.MA_MONHOC,
NAME = MONHOC.TEN_MONHOC,
ID_PARENT = 0
}).Concat
(from MONHOC in db.tbl_MONHOCs
where
(MONHOC.IS_DELETE != 1 ||
MONHOC.IS_DELETE == null) &&
MONHOC.ISBATBUOC == 0
select new
{
ID = ("MH_CON_" + Convert.ToString(MONHOC.ID_MONHOC)),
ID_NAME = MONHOC.ID_MONHOC,
MA_MONHOC = MONHOC.MA_MONHOC,
NAME = MONHOC.TEN_MONHOC,
ID_PARENT = (int?) MONHOC.ID_MONHOC_CHA
}
);
Error
Error Compiling Expression: Error Compiling Expression:
'System.Linq.IQueryable' does not contain a
definition for 'Concat' and the best extension method overload
'System.Linq.ParallelEnumerable.Concat(System.Linq.ParallelQuery,
System.Collections.Generic.IEnumerable)' has some invalid
arguments Instance argument: cannot convert from
'System.Linq.IQueryable' to
'System.Linq.ParallelQuery'
The exception message "clearly" :) tells you that the types of the properties in the anonymous types don't match.
In the first part you have:
ID_PARENT = 0
In the second part:
ID_PARENT = (int?) MONHOC.ID_MONHOC_CHA
These properties should both either be int? or int.
I want to loop through different indexed tables by only passing the initial table as an argument.
I currently have this table:
local table = {
stuff_1 = {
categories = {},
[1] = {
name = 'wui',
time = 300
}
},
stuff_2 = {
categories = {'stuff_10', 'stuff_11', 'stuff_12'},
stuff_10 = {
categories = {},
[1] = {
name = 'peo',
time = 150
},
[2] = {
name = 'uik',
time = 15
},
[3] = {
name = 'kpk',
time = 1230
},
[4] = {
name = 'aer',
time = 5000
}
},
stuff_11 = {
categories = {},
[1] = {
name = 'juio',
time = 600
}
},
stuff_12 = {
categories = {},
[1] = {
name = 'erq',
time = 980
},
[2] = {
name = 'faf',
time = 8170
}
}
}
I wanted to make a recursive function to check if the name in any of those tables was equal to some certain thing and return a string.
The recursivity lies in the idea of updating this table with whatever ammount I'd like (or until a certain limit).
I don't understand exactly what's wrong since when I try:
for k, v in pairs(table) do
print(k, v, #v.categories)
end
It correctly prints:
stuff_2 table: 0x10abb0 3
stuff_1 table: 0x10aab8 0
But when passing the table as a parameter to the the function below, it gives this error:
[string "stdin"]:84: attempt to get length of field 'categories' (a nil value)
Function:
function checkMessage(table)
local i = 1
local message = ""
for k, v in pairs(table) do
if(#v.categories == 0) then
while(v[i]) do
if(v[i].name == 'opd') then
if(v[i].time ~= 0) then
message = "return_1"
else
message = "return_2"
end
end
i = i + 1
end
else
checkMessage(table[k])
end
end
return message
end
EDIT: The problem lies in not ignoring that when using pairs onto the table, this doesn't just have tables with a category subtable but it also has a table named category, if this is ignored then the problem is fixed.
You're recursing into subtables that don't have a categories field. Trying to access categories on them yields nil, which you then try to use the length operator on. Hence your error:
attempt to get length of field 'categories' (a nil value)
If you can't hand trace your app, put in more print statements or get a line level debugger.
How can I represent integer as Binary?
so I can print 7 as 111
You write a function to do this.
num=7
function toBits(num)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=(num-rest)/2
end
return t
end
bits=toBits(num)
print(table.concat(bits))
In Lua 5.2 you've already have bitwise functions which can help you ( bit32 )
Here is the most-significant-first version, with optional leading 0 padding to a specified number of bits:
function toBits(num,bits)
-- returns a table of bits, most significant first.
bits = bits or math.max(1, select(2, math.frexp(num)))
local t = {} -- will contain the bits
for b = bits, 1, -1 do
t[b] = math.fmod(num, 2)
num = math.floor((num - t[b]) / 2)
end
return t
end
There's a faster way to do this that takes advantage of string.format, which converts numbers to base 8. It's trivial to then convert base 8 to binary.
--create lookup table for octal to binary
oct2bin = {
['0'] = '000',
['1'] = '001',
['2'] = '010',
['3'] = '011',
['4'] = '100',
['5'] = '101',
['6'] = '110',
['7'] = '111'
}
function getOct2bin(a) return oct2bin[a] end
function convertBin(n)
local s = string.format('%o', n)
s = s:gsub('.', getOct2bin)
return s
end
If you want to keep them all the same size, then do
s = string.format('%.22o', n)
Which gets you 66 bits. That's two extra bits at the end, since octal works in groups of 3 bits, and 64 isn't divisible by 3. If you want 33 bits, change it to 11.
If you have the BitOp library, which is available by default in LuaJIT, then you can do this:
function convertBin(n)
local t = {}
for i = 1, 32 do
n = bit.rol(n, 1)
table.insert(t, bit.band(n, 1))
end
return table.concat(t)
end
But note this only does the first 32 bits! If your number is larger than 2^32, the result wont' be correct.
function bits(num)
local t={}
while num>0 do
rest=num%2
table.insert(t,1,rest)
num=(num-rest)/2
end return table.concat(t)
end
Since nobody wants to use table.insert while it's useful here
Here is a function inspired by the accepted answer with a correct syntax which returns a table of bits in wriiten from right to left.
num=255
bits=8
function toBits(num, bits)
-- returns a table of bits
local t={} -- will contain the bits
for b=bits,1,-1 do
rest=math.fmod(num,2)
t[b]=rest
num=(num-rest)/2
end
if num==0 then return t else return {'Not enough bits to represent this number'}end
end
bits=toBits(num, bits)
print(table.concat(bits))
>>11111111
function reverse(t)
local nt = {} -- new table
local size = #t + 1
for k,v in ipairs(t) do
nt[size - k] = v
end
return nt
end
function tobits(num)
local t={}
while num>0 do
rest=num%2
t[#t+1]=rest
num=(num-rest)/2
end
t = reverse(t)
return table.concat(t)
end
print(tobits(7))
# 111
print(tobits(33))
# 100001
print(tobits(20))
# 10100
local function tobinary( number )
local str = ""
if number == 0 then
return 0
elseif number < 0 then
number = - number
str = "-"
end
local power = 0
while true do
if 2^power > number then break end
power = power + 1
end
local dot = true
while true do
power = power - 1
if dot and power < 0 then
str = str .. "."
dot = false
end
if 2^power <= number then
number = number - 2^power
str = str .. "1"
else
str = str .. "0"
end
if number == 0 and power < 1 then break end
end
return str
end
May seem more verbose but it is actually faster than other functions that use the math library functions. Works with any number, be it positive/negative/fractional...
local function tobits(num, str) -- tail call
str = str or "B"
if num == 0 then return str end
return tobits(
num >> 1 , -- right shift
((num & 1)==1 and "1" or "0") .. str )
end
This function uses a lookup table to print a binary number extracted from a hex representation. All using string manipulation essentially. Tested in lua 5.1.
local bin_lookup = {
["0"] = "0000",
["1"] = "0001",
["2"] = "0010",
["3"] = "0011",
["4"] = "0100",
["5"] = "0101",
["6"] = "0110",
["7"] = "0111",
["8"] = "1000",
["9"] = "1001",
["A"] = "1010",
["B"] = "1011",
["C"] = "1100",
["D"] = "1101",
["E"] = "1110",
["F"] = "1111"
}
local print_binary = function(value)
local hs = string.format("%.2X", value) -- convert number to HEX
local ln, str = hs:len(), "" -- get length of string
for i = 1, ln do -- loop through each hex character
local index = hs:sub(i, i) -- each character in order
str = str .. bin_lookup[index] -- lookup a table
str = str .. " " -- add a space
end
return str
end
print(print_binary(45))
#0010 1101
print(print_binary(65000))
#1111 1101 1110 1000
This maybe not work in lua that has no bit32 library
function toBinary(number, bits)
local bin = {}
bits = bits - 1
while bits >= 0 do --As bit32.extract(1, 0) will return number 1 and bit32.extract(1, 1) will return number 0
--I do this in reverse order because binary should like that
table.insert(bin, bit32.extract(number, bits))
bits = bits - 1
end
return bin
end
--Expected result 00000011
print(table.concat(toBinary(3, 8)))
This need at least lua 5.2 (because the code need bit32 library)
As by Dave, but with filled empty bits:
local function toBits(num, bits)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
bits = bits or 8
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=math.floor((num-rest)/2)
end
for i = #t+1, bits do -- fill empty bits with 0
t[i] = 0
end
return t
end
for i = 0, 255 do
local bits = toBits(i)
print(table.concat(bits, ' '))
end
Result:
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
1 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
1 0 1 0 0 0 0 0
...
0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1