check each character from a string by pgsql function - function

I want to make a function which will check each character of a string.
For example, lets take a word "pppppoooossssttt", in this case the function will return a warning if same character repeated for more that 2 times. Here 'p' is repeated for 5 times. So the function will return a warning message.

If you're able to install plpython on your setup, this is what I would do. Then you could simply place this test inside a "WHERE" clause of a standard SQL function. It's immutable so it will only be called once, and it always returns True so it won't affect the results of a SQL query. Postgres has had some pretty shaky python implementations but either they or EnterpriseDB cleaned things up in the latest release.
CREATE OR REPLACE FUNCTION two_or_less(v text)
RETURNS BOOLEAN AS $$
#If the string is two characters
#or less, we can quit now.
ct = len(v)
if ct < 3:
return True
import plpy
warned = set()
a,b,c = v[:3]
for d in v[2:]:
if a == b == c:
if a not in warned:
warned.add(a)
plpy.warning('The character %r is repeated more than twice in a row.' % a)
a,b,c = b,c,d
return True
$$ LANGUAGE 'plpython3u' IMMUTABLE;

Related

Passing Arguments within If Statement

I'm trying to pass arguments between two files, and am encountering issues. I'm trying to parse a message for the word 'foo' in it, and create a function that will check if the message is only 'foo' or perhaps is a word like 'foot', which contains foo but isn't the word foo. Here's the two files
test2.py
import os, sys
from functiontest import function
message = 'foo'
check = 0
if 'foo' in message:
function(message,check)
print(check)
print('bar')
else:
check = 0
if check == 0:
print('foo not recognized')
and the function file
functiontest.py
import os, sys
def function(a,b):
print('checking message')
a = a.split()
print(a)
if a[0] == 'foo':
b = 1
print(b)
return b
else:
b = 0
return b
When run, it indicates that when b is set to 1 and passes it, it doesn't get passed correctly and remains 0. I want it to pass the argument check to be 1 if it is detected that the word isn't exactly 'foo' so that the message will appear saying that 'foo is not detected'. What am I doing wrong?
Follow up question: Once check is confirmed as 0 within the if statement, is there a way to break the statement and not execute the next lines that are within that if statement and rather skip to the else statement? I would prefer to include this somehow in the function to make the main code look cleaner, because I could include more embedded if statements but I want to avoid that if possible.
You're throwing away the return value of function, then printing check, which was never changed from the original value of 0. I believe your intent was to reassign check with the return value of the function:
check = function(message,check)
print(check)

Is it possible to figure out the return value of a function in lua? Or whether or not a function returns anything?

Lets say for example I have made a function and it's purpose is to analyze another function supplied as a parameter and return whether or not the function specified will return anything, and if so what value it will return.
local function CheckFunctionReturn(func)
--return whether func would return anything.
end
local function myFunc()
return 123;
end
CheckFunctionReturn(myFunc);
I am stuck with this. Perhaps there is a function in the debug library that can help? I would appreciate any help.
None of the functions in the debug library can do this. Instead you need to analyse the source code or the bytecode to find out what the program will do. There are some resources available on the Lua wiki, and others have given good suggestions above as well.
Note that the problem of whether an arbitrary function will return or not when it is given arbitrary input is the halting problem, and was proven to be impossible to solve in the general case by Alan Turing back in 1936. However, for simple functions and/or inputs it is solvable, so if your specific case is simple enough you might be able to do it.
This is quick-and-dirty solution (only Lua 5.1, only LE architecture), which is likely to work in most cases, but not always.
It only answers the question "Whether or not this function would return some values?"
local function CheckFunctionReturn(func)
-- returns true if func would return anything
local d = string.dump(func)
assert(d:sub(1,5) == "\27LuaQ") -- only Lua 5.1
-- search for code before first "return" (0x0080001E)
d = d:match"^.-\30%z\128%z"
-- search for "return" with non-zero number of returned values
for pos = #d % 4 + 1, #d, 4 do
local b1, b2, b3, b4 = d:byte(pos, pos+3)
local dword = b1 + 256 * (b2 + 256 * (b3 + 256 * b4))
local OpCode, BC = dword % 64, math.floor(dword/16384)
local B, C = math.floor(BC/512), BC % 512
if OpCode == 30 and C == 0 and B ~= 1 then
return true
end
end
return false
end
print(CheckFunctionReturn(aFunctionToBeAnalyzed));
local function CheckFunctionReturn(func)
print(type(func()))
end
local function myFunc()
return 123;
end
CheckFunctionReturn(myFunc);
Am I missing something?
The Lua built-in debug API docs says
The return hook: is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. There is no standard way to access the values to be returned by the function.

How to get Postgres function name as well as function specific name from pg_catalog.pg_proc?

Since Postgres supports function overloading, getting function name as well as function specific name(System generated without duplicates) is more meaning full.
Assume i have 2 functions in the name as Func1 which are overloaded as shown below,
CREATE FUNCTION "Schema"."Func1"(IN param1 INTEGER,
IN Param2 CHAR)
RETURNS INTEGER
AS $BODY$
begin
return param1+1;
end $BODY$
LANGUAGE PLPGSQL;#
CREATE FUNCTION "Schema"."Func1"(IN param1 INTEGER)
RETURNS INTEGER
AS $BODY$
begin
return param1+1;
end $BODY$
LANGUAGE PLPGSQL;#
How do i load the functions as well as input parameters correctly from pg_catalog.pg_proc.
With the help of information_schema.routines, there is a way to load function 1)specific_name 2) routine_name
But many other attributes are missing in information_schema.routines like 1) isWindow function 2) isStrict function 3) isProRetSet function
So is there some other means to get the function specific_name from pg_catalog.....
A general method is to use psql -E or set ECHO_HIDDEN inside psql and look at the queries it generates for backslash commands.
For instance, \df "Func1" produces this with PostgreSQL 9.1:
SELECT n.nspname as "Schema",
p.proname as "Name",
pg_catalog.pg_get_function_result(p.oid) as "Result data type",
pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
CASE
WHEN p.proisagg THEN 'agg'
WHEN p.proiswindow THEN 'window'
WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
ELSE 'normal'
END as "Type"
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE p.proname ~ '^(Func1)$'
AND pg_catalog.pg_function_is_visible(p.oid)
ORDER BY 1, 2, 4;
which gives you directions about how to get the different function signatures associated to the name "Func1"
The same with \df+ would lead to the other attributes, like volatility.

Lua - Execute a Function Stored in a Table

I was able to store functions into a table. But now I have no idea of how to invoke them. The final table will have about 100 calls, so if possible, I'd like to invoke them as if in a foreach loop. Thanks!
Here is how the table was defined:
game_level_hints = game_level_hints or {}
game_level_hints.levels = {}
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
},
[on_scene("scene1")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
}
}
end
Aaand the function definitions:
function on_scene(sceneId)
-- some code
return sceneId
end
function talk(areaId)
-- some code
return areaId
end
EDIT:
I modified the functions so they'll have a little more context. Basically, they return strings now. And what I was hoping to happen is that at then end of invoking the functions, I'll have a table (ideally the levels table) containing all these strings.
Short answer: to call a function (reference) stored in an array, you just add (parameters), as you'd normally do:
local function func(a,b,c) return a,b,c end
local a = {myfunc = func}
print(a.myfunc(3,4,5)) -- prints 3,4,5
In fact, you can simplify this to
local a = {myfunc = function(a,b,c) return a,b,c end}
print(a.myfunc(3,4,5)) -- prints 3,4,5
Long answer: You don't describe what your expected results are, but what you wrote is likely not to do what you expect it to do. Take this fragment:
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
}
}
end
[This paragraph no longer applies after the question has been updated] You reference on_scene and talk functions, but you don't "store" those functions in the table (since you explicitly referenced them in your question, I presume the question is about these functions). You actually call these functions and store the values they return (they both return nil), so when this fragment is executed, you get "table index is nil" error as you are trying to store nil using nil as the index.
If you want to call the function you stored in game_level_hints.levels["level0"], you just do game_level_hints.levels["level0"]()
Using what you guys answered and commented, I was able to come up with the following code as a solution:
asd = game_level_hints.levels["level0"]()
Now, asd contains the area strings I need. Although ideally, I intended to be able to access the data like:
asd[1][1]
accessing it like:
asd["scene0"][1]
to retrieve the area data would suffice. I'll just have to work around the keys.
Thanks, guys.
It's not really clear what you're trying to do. Inside your anonymous function, you're returning a table that uses on_scene's return value as keys. But your on_scene doesn't return anything. Same thing for talk.
I'm going to assume that you wanted on_scene and talk to get called when invoking each levels in your game_level_hints table.
If so, this is how you can do it:
local maxlevel = 99
for i = 0, maxlevel do
game_level_hints.levels["level" .. i] = function()
on_scene("scene" .. i)
talk("hint" .. i)
end
end
-- ...
for levelname, levelfunc in pairs(game_level_hints.levels) do
levelfunc()
end

Lua functions -- a simple misunderstanding

I'm trying to develop a function which performs math on two values which have the same key:
property = {a=120, b=50, c=85}
operator = {has = {a, b}, coefficient = {a = 0.45}}
function Result(x) return operator.has.x * operator.coefficient.x end
print (Result(a))
error: attempt to perform arithmetic on field 'x' (a nil value)
The problem is that the function is attempting math on literally
"operator.has.x" instead of "operator.has.a".
I'm able to call a function (x) return x.something end, but if I try function (x) something.x i get an error. I need to improve my understanding of functions in Lua, but I can't find this in the manuals.
I'm not exactly sure what you're trying to do, but here is some working code that is based on your code:
property = {a=120, b=50, c=85}
operator = {has = {a=2, b=3}, coefficient = {a = 0.45}}
function Result(x) return operator.has[x] * operator.coefficient[x] end
print (Result('a'))
Prints '0.9'
This is a common gotcha for newcomers to the language. Buried in the Lua manual somewhere:
To represent records, Lua uses the field name as an index. The
language supports this representation by providing a.name as syntactic
sugar for a["name"].
This explains why your function Result(x) is failing. If you translate the syntactic sugar, your function becomes:
function Result(x)
return operator.has['x'] * operator.coefficient['x']
end
Geary already offered a solution to this so I won't reiterate it here.