case types boolean and double precision cannot be matched in Postgres - postgresql

Query : if b is credit (i.e 0 or greater than 0), then the values should be a. Otherwise (a+b), and negative values should be zero.
My query condition is
Case when(b>=0) Then (a) Else (SUM(a+b)>0 End as Difference
But I'm getting this error
Error : CASE Types boolean and double precision cannot be matched
It would be a great pleasure if someone assist for the query solution. I'm using Postgres as database.

There is a syntax error in your expression; the number of opening and closing parentheses doesn't match.
But a is a number, while a + b > 0 is a boolean value (“true” or “false”), so PostgreSQL complains that it cannot determine what the type of your case expression should be.
According to your description, I would use
CASE WHEN b >= 0
THEN a
ELSE greatest(a + b, 0)
END

Related

Checking whether values are Upper case or lower case

I'm trying to build a function in q/kdb+ that can detect whether the string passed to the function is Upper case (True) OR lower case (false)
I have done several attempts but I'm constantly hitting a road block
Here's my function, would appreciate the help. TIA
isAllCaps: {[input] if[input = lower; show 0b; show 1b]}
The above function basically takes an input as specified. It then checks from the if statement whether it is lower, if it is lower then it should return a false(0b), if not then return a true (1b). Really struggling with something so simple here. I'm just getting the following error:
evaluation error:
type
[1] isAllCaps:{[input] if[input = lower; show 0b; show 1b]}
^
[0] isAllCaps"a"
I have also tried other methods but only certain inputs were coming out to be successful.
For instance:
isAllCaps: {[x] if[ x = upper type 10h; show 1b; show 0b]}
This equates to if x is upper type string, show true, else show false. Again, getting a type error. Idk why? All the tests are in strings i.e., "John_Citizen" etc. etc.
EDIT
Tried this but I'm getting 2 outputs.
isAllCaps: {[L] if[L = lower L; show 0b; show 1b] } Am I missing something?
Try following code:
isAllCaps: {[L] show L~upper L};
It shows 1b if string is uppercase, and 0b otherwise.
There are 2 mistakes in you code
~ should be used to compare strings. = does character-wise comparison. I.e. "aa"~"aa" gives 1b, but "aa"="aa" gives 11b
Use if-else, instead of if. See 10.1.1 Basic Conditional Evaluation for more details
You can use the in-built uppercase alphabet .Q.A to achieve what you want:
{all x in .Q.A}
This lambda will return 1b if the input string consists only of capital letters and false otherwise.
Start by removing some misapprehensions.
lower returns the lower case of its argument.
show displays and returns its result. You can use it as you have to ensure the function’s result is printed on the console, but it is not required as, for example return would be in JavaScript.
If you have a boolean as the result of a test, that can just be your result.
Compare strings for equality using Match ~ rather than Equals
That said, two strategies: test for lower-case chars .Q.a, or convert to upper case and see if there is a difference.
q){not any x in .Q.a}"AAA_123"
1b
q){not any x in .Q.a}"AaA_123"
0b
The second strategy could hardly be simpler to write:
q){x~upper x}"AaA_123"
0b
q){x~upper x}"AAA_123"
1b
Together with the Apply . operator, the Zen monks construction gives you fast ‘point-free’ code – no need for a lambda:
q).[~] 1 upper\"AaA_123"
0b
q).[~] 1 upper\"AAA_123"
1b

How to use length and rlike using logical operator inside when clause

Want to check if the column has values that have certain length and contains only digits.
The problem is that the .rlike or .contains returns a Column type. Something like
.when(length(col("abc")) == 20 & col("abc").rlike(...), myValue)
won't work as col("abc").rlike(...) will return Column and unlike length(col("abc")) == 20 which returns Boolean (length() however also returns Column). How do I combine the two?
After doing a bit of searching in compiled code, found this
def when(condition : org.apache.spark.sql.Column, value : scala.Any) : org.apache.spark.sql.Column
Therefore the conditions in when must return Column type. length(col("abc")) == 20 was evaluating to Boolean.
Also, found this function with the following signature
def equalTo(other : scala.Any) : org.apache.spark.sql.Column
So, converted the whole expression to this
.when(length(col("abc")).equalTo(20) && col("abc").rlike(...), myValue)
Note that the logical operator is && and not &.
Edit/Update : #Histro's comment is correct.

"operator symbol not allowed for generic subprogram" from Ada

I want to make subprogram for adding array's elements with Ada.
subprogram "Add_Data" have 3 parameters-
first parameter = generic type array (array of INTEGER or array of REAL)
second parameter = INTEGER (size of array)
third parameter = generic type sum (array of INTEGER -> sum will be INTEGER, array of REAL -> sum will be REAL)
I programmed it from ideone.com.
(I want to see just result by array of INTEGER. After that, I will test by array of REAL)
With Ada.Text_IO; Use Ada.Text_IO;
With Ada.Integer_Text_IO; Use Ada.Integer_Text_IO;
procedure test is
generic
type T is private;
type Tarr is array (INTEGER range <>) of T;
--function "+" (A,B : T) return T;
--function "+" (A, B : T) return T is
--begin
-- return (A+B);
--end "+";
procedure Add_Data(X : in Tarr; Y : in INTEGER; Z : in out T);
procedure Add_Data(X : in Tarr; Y : in INTEGER; Z : in out T) is
temp : T;
count : INTEGER;
begin
count := 1;
loop
temp :=temp+ X(count); //<-This is problem.
count := count + 1;
if count > Y then
exit;
end if;
end loop;
Z:=temp;
end Add_Data;
type intArray is array (INTEGER range <>) of INTEGER;
intArr : intArray := (1=>2, 2=>10, 3=>20, 4=>30, 5=>8);
sum : INTEGER;
procedure intAdd is new Add_Data(Tarr=>intArray, T=>INTEGER);
begin
sum := 0;
intAdd(intArr, 5, sum);
put (sum);
end test;
when I don't overload operator "+", It makes error.
"There is no applicable operator "+" for private type "T" defined."
What can I do for this?
If a generic’s formal type is private, then nothing in the generic can assume anything about the type except that it can be assigned (:=) and that it can be compared for equality (=) and inequality (/=). In particular, no other operators (e.g. +) are available in the generic unless you provide them.
The way to do that is
generic
type T is private;
with function "+" (L, R : T) return T is <>;
This tells the compiler that (a) there is a function "+" which takes two T’s and returns a T; and (b) if the actual T has an operator "+" which matches that profile, to allow it as the default.
So, you could say
procedure intAdd is new Add_Data (T => Integer, ...
or, if you didn’t feel like using the default,
procedure intAdd is new Add_Data (T => Integer, "+" => "+", ...
In addition to not knowing how to declare a generic formal subprogram (Wright has shown how to do this for functions), your code has a number of other issues that, if addressed, might help you move from someone who thinks in another language and translates it into Ada into someone who actually uses Ada. Presuming that you want to become such a person, I will point some of these out.
You declare your array types using Integer range <>. It's more common in Ada to use Positive range <>, because people usually refer to positions starting from 1: 1st, 2nd, 3rd, ...
Generics are used for code reuse, and in real life, such code is often used by people other than the original author. It is good practice not to make unstated assumptions about the values clients will pass to your operations. You assume that, for Y > 0, for all I in 1 .. Y => I in X'range and for Y < 1, 1 in X'range. While this is true for the values you use, it's unlikely to be true for all uses of the procedure. For example, when an array is used as a sequence, as it is here, the indices are immaterial, so it's more natural to write your array aggreate as (2, 10, 20, 30, 8). If I do that, Intarr'First = Integer'First and Intarr'Last = Integer'First + 4, both of which are negative. Attempting to index this with 1 will raise Constraint_Error.
Y is declared as Integer, which means that zero and negative values are acceptable. What does it mean to pass -12 to Y? Ada's subtypes help here; if you declare Y as Positive, trying to pass non-positive values to it will fail.
Z is declared mode in out, but the input value is not referenced. This would be better as mode out.
Y is not needed. Ada has real arrays; they carry their bounds around with them as X'First, X'Last, and X'Length. Trying to index an array outside its bounds is an error (no buffer overflow vulnerabilities are possible). The usual way to iterate over an array is with the 'range attribute:
for I in X'range loop
This ensures that I is always a valid index into X.
Temp is not initialized, so it will normally be initialized to "stack junk". You should expect to get different results for different calls with the same inputs.
Instead of
if count > Y then
exit;
end if;
it's more usual to write exit when Count > Y;
Since your procedure produces a single, scalar output, it would be more natural for it to be a function:
generic -- Sum
type T is private;
Zero : T;
type T_List is array (Positive range <>) of T;
with function "+" (Left : T; Right : T) return T is <>;
function Sum (X : T_List) return T;
function Sum (X : T_List) return T is
Result : T := Zero;
begin -- Sum
Add_All : for I in X'range loop
Result := Result + X (I);
end loop Add_All;
return Result;
end Sum;
HTH

Why does system verilog max() and min() functions return a queue and not a single element?

I noticed this interesting thing about the max() and min() functions in SV LRM (1800-2012) 7.12 (Array manipulation methods). I tried out the max() and min() functions in a dummy SV file
int a[3] = {0,5,5};
int q[$];
int b;
q = a.max(); // legal
b = a.max(); // illegal
The illegal statement error was
Incompatible complex type assignment
Type of source expression is incompatible with type of target expression.
Mismatching types cannot be used in assignments, initializations and
instantiations. The type of the target is 'int', while the type of the
source is 'int$[$]'.
So I commented out the illegal statement and tested it. It compiled and ran fine but I was hoping to get some more insight as to why the function returns a queue and not a single element - I printed out the contents of q and the size, but the size is still 1 and 5 is being printed just once. Kind of redundant then to make the max() and min() functions return a queue ?
The "SystemVerilog for Verification" book by Chris Spear and Greg Tumbush has a good explanation on this topic in Chapter 2.6.2, which I am quoting below:
"The array locator methods find data in an unpacked array. At first
you may wonder why these return a queue of values. After all, there
is only one maximum value in an array. However, SystemVerilog needs a
queue for the case when you ask for a value from an empty queue or
dynamic array."
It returns a queue to deal with empty queues and when the with () conditions have no matches. The the empty queue return is a a way to differentiate a true match from no matches.
Consider the below code. to find the minimum value of a that is greater than 5. a has data but none of its entries have above 5. b is empty, so it will return an empty. c will return 7.
int a[3] = '{0,5,5};
int b[$] = '{};
int c[4] = '{0,15,5,7};
int q[$];
q = a.min() with (item > 5); // no items >5, will return an empty queue
q = b.min(); // queue is empty, will return an empty queue
q = c.min() with (item > 5); // will return a queue of size 1 with value 7
I believe the example results as per Greg's answer is not correct.
As per System Verilog Language:
min() returns the element with the minimum value or whose expression evaluates to a minimum.
max() returns the element with the maximum value or whose expression evaluates to a maximum.
So, when with expression is evaluated, the resultant value will be:
a.min() with (item > 5); {0,0,0} -> Minimum is 0 and corresponding item is 5.
c.min() with (item > 5); {0,1,0,1}-> Minimum is 0 and corresponding item is 5.
Since, example demonstrates the usage of min, the result will be:
q = a.min() with (item > 5); // A queue of size 1 with value 5.
q = c.min() with (item > 5); //A queue of size 1 with value 5.

|| operators must be convertible to logical scalar values in case of an empty matrix

Consider the following code
t = ones(3,5)
Ind2save = find(t(1,:) == 0,1,'first')
So for example I am trying to find if even the first zero of the first row, so if the first element is a non zero then
if(Ind2save ~= 1 )
disp('no')
end
now for the above condition it doesn't display 'no' because the condition is not fulfilled but because all the rows are filled and Ind2save is an empty matrix so we another condition to check if it is fully filled then
if(Ind2save > 1 || isempty(Ind2save))
disp('no')
end
I get the following error
Operands to the || and && operators must be convertible to logical scalar values.
I searched for the reasons due to which this error is caused and in majority of the cases people were comparing two vectors so a better idea was to replace || with | but in my case the conditions are never vectors but Ind2save > 1 returns an empty matrix , does anyone know why is the reason for that? How can I accommodate both the conditions?
The issue is because in your case Ind2save is empty ([]) therefore the first part of your condition can't be used with || since [] > 1 doesn't yield a logical scalar (it results in []).
In order to fix this, you can to flip the order of your conditions such that you check if the array is empty first.
if isempty(Ind2save) || Ind2save > 1
The reason that this works is that if Ind2Save is empty, then the first condition evaluates to true therefore short-circuiting the rest of the checks.
You may have other issues if for some reason Ind2save is a vector. In that case you could need to so something to convert it to a logical scalar:
if isempty(Ind2save) || ismember(1, Ind2save)