oracle has a nice built in function for doing if null, however I want to do if = 0; is there a simple way to do this?
nvl(instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' '),
length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))))
This is going as a parameter to a substr function.
If instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' ') is != 0 then I want that value, otherwise I want the value of length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))
is there an easy way to do this?
You can use NVL(NULLIF(A,'0'), B)
I found both answers hard to read because of the extra verbiage from the original post. Summarizing Conrad and Craig's answers:
To replicate nvl(A,B) but for 0 instead of null, you can do:
WHEN A != 0 THEN
A
ELSE
B
END
or Craig's more compact (but harder for others to read):
NVL(NULLIF(A,0),B)
I think that the following would also work:
DECODE(A,0,B,A)
I think you'll need to use CASE
e.g.
WHEN instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' ') != 0 THEN
length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))
ELSE
Some Default
END as foo
You could technically do this with less typing as:
nvl(
nullif(instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' '),0),
length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))
)
However, I would typically side with Conrad and advise you to use CASE so it is easier to tell what the intent of the code is for future maintenance.
Related
this ruby code works, but is there a more conventional or simplified way to write it:
options['host'] = begin
a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5'
end
I just feel like the code is a smell but I cannot put my finger on it.
Thanks.
You don't need begin..end here.
options['host'] = a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5'
I'd probably put parentheses around right side. Not necessary, just for clarity.
options['host'] = (a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5')
Usually symbols are used as hash keys because they save memory and are a little faster for comparisons, and the begin..end block is not necessary. Thus it becomes:
options[:host] = (a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5')
This is a relatively long while, in my head the following parses easier:
options[:host] = 'doric-server5'
options[:host] = 'jaxon-server16.jaxon.local' if a == :jaxon
An iteration on top of that, is that you have what appears to be semi-hardcoded values (jaxon-server16.jaxon.local and doric-server5). You should store these in constants or another data structure in order to have these gathered in one place. For instance, if doric-server5 becomes doric-server6 one day, you'll only have to change it in the top of a class or file somewhere. Furthermore, it makes the code easier to read since they now have more humane names of whatever they represent.
# somewhere else:
JAXON_SERVER = 'jaxon-server16.jaxon.local'
DORIC_SERVER = 'doric-server5'
options[:host] = DORIC_SERVER
options[:host] = JAXON_SERVER if a == :jaxon
Since we've dealt with the original motivation to make it two lines, we could go back to one, nice line:
options[:host] = (a == :jaxon ? JAXON_SERVER : DORIC_SERVER)
If you have a lot of these kinds of statements, you could make a server hash, where e.g. server[:jaxon] = 'jaxon-server16.jaxon.local', but if you just have two, two string constants are fine.
In some cases it's nicer to have the default option (in this case DORIC_SERVER) appear wherever it would default to that value, instead of setting the host to the default value directly. Hash#fetch takes two arguments: a key, and a value to default to, if that key doesn't exist.
options[:host] = JAXON_SERVER if a == :jaxon
# somewhere else:
options.fetch(:host, DORIC_SERVER)
Without more information, it's hard to say which approach is the best in your case. :-)
This is another way to write it
options['host'] = case a
when :jaxon
'jaxon-server16.jaxon.local'
else
'doric-server5'
end
It has a lot more lines but i like its readability. It also makes it easy to add more hosts:
options['host'] = case a
when :jaxon
'jaxon-server16.jaxon.local'
when :staging
'staging-server1'
else
'doric-server5'
end
If you want to surround it with something for readability, you can share a pair of parentheses with the Hash#store method.
options.store( "host",
a == :jaxon ? "jaxon-server16.jaxon.local" : "doric-server5"
)
can anyone recommend software (preferably for mac) or a web based tool, that can be used to evaluate logic expressions?
For example I would like to be able to quickly test whether two expressions like:
$a = 'foo';
$b = 'bar';
$c = 'foo';
( !(($a == $c) && ($b == $c)) )
// and
( ($a != $c) || ($b != c$) )
are interchangeable or not.
And also, is there generally an agreed upon best practice in relation to how to construct such expressions? For example to try to minimize the use of the negation, the order of the elements or something like that?
Sometimes I find myself struggling a bit with these things :)
You can also use Wolfram Alpha
https://www.wolframalpha.com/input/?i=P+%26%26+(Q+%7C%7C+R)&lk=3
or
https://www.dcode.fr/boolean-expressions-calculator
You can use something like http://www-cs-students.stanford.edu/~silver/truth/ and compare the generated truth tables.
I like this site which does exactly what you are looking for, but it only supports limited logical operators:
https://electronics-course.com/boolean-algebra
I was coding here the other day, writing a couple of if statements with integers that are always either 0 or 1 (practically acting as bools). I asked myself:
When testing for positive result, which is better; testing for int == 1 or int != 0?
For example, given an int n, if I want to test if it's true, should I use n == 1 or n != 0?
Is there any difference at all in regards to speed, processing power, etc?
Please ignore the fact that the int may being more/less than 1/0, it is irrelevant and does not occur.
Human's brain better process statements that don't contain negations, which makes "int == 1" better way.
It really depends. If you're using a language that supports booleans, you should use the boolean, not an integer, ie:
if (value == false)
or
if (value == true)
That being said, with real boolean types, it's perfectly valid (and typically nicer) to just write:
if (!value)
or
if (value)
There is really very little reason in most modern languages to ever use an integer for a boolean operation.
That being said, if you're using a language which does not support booleans directly, the best option here really depends on how you're defining true and false. Often, false is 0, and true is anything other than 0. In that situation, using if (i == 0) (for false check) and if (i != 0) for true checking.
If you're guaranteed that 0 and 1 are the only two values, I'd probably use if (i == 1) since a negation is more complex, and more likely to lead to maintenance bugs.
If you're working with values that can only be 1 or 0, then I suggest you use boolean values to begin with and then just do if (bool) or if (!bool).
In language where int that are not 0 represents the boolean value 'true', and 0 'false', like C, I will tend to use if (int != 0) because it represents the same meaning as if (int) whereas int == 1 represents more the integer value being equal to 1 rather than the boolean true. It may be just me though. In languages that support the boolean type, always use it rather than ints.
A Daft question really. If you're testing for 1, test for 1, if you're testing for zero, test for zero.
The addition of an else statement can make the choice can seem arbitrary. I'd choose which makes the most sense, or has more contextual significance, default or 'natural' behaviour suggested by expected frequency of occurrence for example.
This choice between int == 0 and int != 1 may very well boil down to subjective evaluations which probably aren't worth worrying about.
Two points:
1) As noted above, being more explicit is a win. If you add something to an empty list you not only want its size to be not zero, but you also want it to be explicitly 1.
2) You may want to do
(1 == int)
That way if you forget an = you'll end up with a compile error rather than a debugging session.
To be honest if the value of int is just 1 or 0 you could even say:
if (int)
and that would be the same as saying
if (int != 0)
but you probably would want to use
if (int == 1)
because not zero would potentially let the answer be something other than 1 even though you said not to worry about it.
If only two values are possible, then I would use the first:
if(int == 1)
because it is more explicit. If there were no constraint on the values, I would think otherwise.
IF INT IS 1
NEXT SENTENCE
ELSE MOVE "INT IS NOT ONE" TO MESSAGE.
As others have said, using == is frequently easier to read than using !=.
That said, most processors have a specific compare-to-zero operation. It depends on the specific compiler, processor, et cetera, but there may be an almost immeasurably small speed benefit to using != 0 over == 1 as a result.
Most languages will let you use if (int) and if (!int), though, which is both more readable and get you that minuscule speed bonus.
I'm paranoid. If a value is either 0 or 1 then it might be 2. May be not today, may be not tomorrow, but some maintenance programmer is going to do something weird in a subclass. Sometimes I make mistakes myself [shh, don't tell my employer]. So, make the code say tell me that the value is either 0 or 1, otherwise it cries to mummy.
if (i == 0) {
... 0 stuff ...
} else if (i == 1) {
... 1 stuff ...
} else {
throw new Error();
}
(You might prefer switch - I find its syntax in curly brace language too heavy.)
When using integers as booleans, I prefer to interpret them as follows: false = 0, true = non-zero.
I would write the condition statements as int == 0 and int != 0.
I would say it depends on the semantics, if you condition means
while ( ! abort ) negation is ok.
if ( quit ) break; would be also ok.
if( is_numeric( $int ) ) { its a number }
elseif( !$int ) { $int is not set or false }
else { its set but its not a number }
end of discussion :P
I agree with what most people have said in this post. It's much more efficient to use boolean values if you have one of two distinct possibilities. It also makes the code a lot easier to read and interpret.
if(bool) { ... }
I was from the c world. At first I don't understand much about objective-c. After some while, I prefer something like:
if (int == YES)
or
if (int == NO)
in c, i.e.:
if (int == true)
if (int == false)
these days, I use varchar instead of integer as table keys too, e.g.
name marital_status
------ --------------
john single
joe married
is a lot better than:
name marital_status
------ --------------
john S
joe M
or
name marital_status
------ --------------
john 1
joe 2
(Assuming your ints can only be 1 or 0) The two statements are logically equivalent. I'd recommend using the == syntax though because I think it's clearer to most people when you don't introduce unnecessary negations.
I have a GUI which uses a selection from a popupmenu in another callback. Is there a way to return the selected value of the popupmenu in only one line without creating any temporary variables? I've tried several solutions, but I've only managed two lines with one temporary variable:
Three lines:
list=get(handles.popupmenu1,'String');
val=get(handles.popupmenu1,'Value');
str=list{val};
Two lines:
temp=get(handles.popupmenu1,{'String','Value'});
str=temp{1}{temp{2}};
Can anyone shave it down to one?
PS, It's a dynamic menu, so I can't just use get(handles.popupmenu1,'Value') and ignore the string component altogether.
Here's a one-liner:
str = getCurrentPopupString(handles.popupmenu1);
And here's the definition of getCurrentPopupString
function str = getCurrentPopupString(hh)
%# getCurrentPopupString returns the currently selected string in the popupmenu with handle hh
%# could test input here
if ~ishandle(hh) || strcmp(get(hh,'Type'),'popupmenu')
error('getCurrentPopupString needs a handle to a popupmenu as input')
end
%# get the string - do it the readable way
list = get(hh,'String');
val = get(hh,'Value');
if iscell(list)
str = list{val};
else
str = list(val,:);
end
I know that's not the answer you were looking for, but it does answer the question you asked :)
I know this is stupid, but I couldn't resist:
list=get(handles.popupmenu1,'String'); str=list{get(handles.popupmenu1,'Value')};
I know that's not what you meant, but like the other answers above, it does answer your question... :-)
To make it a one-liner, I would simply create my own function (i.e. getMenuSelection) like Jonas illustrates in his answer. If you really want a true one-liner, here's one using CELLFUN:
str = cellfun(#(a,b) a{b},{get(handles.popupmenu1,'String')},{get(handles.popupmenu1,'Value')});
Very ugly and hard to read. I'd definitely go with writing my own function.
EDIT: And here's a slightly shorter (yet still equally ugly) one-liner using FEVAL:
str = feval(#(x) x{1}{x{2}},get(handles.popupmenu1,{'String','Value'}));
var results = from formNumber in context.DetailTM
join c in context.ClaimPeriodTM on formNumber.ClaimPeriod equals c.Cid
where formNumber.FormNumber.StartsWith(fNumber)
&& formNumber.RegistrationNumber != registrationNumber
select new { RegNo = formNumber.RegistrationNumber,
CP = c.ClaimPeriod, FormNo = formNumber.FormNumber };
The AND CLAUSE with .StartsWith Doesn't work. If I use == operator the query works fine. I tried adding brackets to the where clause but it didn't help. Any idea what is missing. Thank you in Advance.
Try something very basic like "&& true == false" and see if that fails. Also reverse the order. If you reverse the order, is it still the second clause that fails?
There's nothing about StartsWith that should cause this behavior. There's something else going on here. Trim and move elements until you isolate the real bug.
What is the database type for FormNumber? If its char (and not varchar), then you may have to trim one or both sides of the comparison.
where
formNumber.FormNumber.Trim().StartsWith(fNumber.Trim())
&& formNumber.RegistrationNumber != registrationNumber
Same as jrummells answer, just targetted by the additional comments.
formNumber.RegistrationNumber != registrationNumber
Check the database types here. If they are fixed length (char or nchar), you may need to do some trimming.