Check if ArgParse optional argument is set or not (in Julia) - julia

This is essentially the same question as: Check if argparse optional argument is set or not, but in Julia, using Julia's ArgParse module.
Given an argument that takes a value, I want to know if its value was given or not.

In short, once you have parsed the arguments, you can check if an argument was set as parsed_args["argname"] == nothing (will return true if it was not set).
Find bellow a self-contained example (sightly modified example1 from ArgParse.jl) with 2 arguments that prints true if an argument was not set (just replace == with != for the opposite behaviour):
using ArgParse
function main(args)
# initialize the settings (the description is for the help screen)
s = ArgParseSettings(description = "Example usage")
#add_arg_table s begin
"--opt1" # an option (will take an argument)
"arg1" # a positional argument
end
parsed_args = parse_args(s) # the result is a Dict{String,Any}
println(parsed_args["arg1"] == nothing)
println(parsed_args["opt1"] == nothing)
end
main(ARGS)
And example command line calls (assuming above is stored in test.jl):
>>> julia test.jl
true
true
>>> julia test.jl 5
false
true
>>> julia test.jl 5 --opt1=6
false
false
>>> julia test.jl --opt1=6
true
false
However, sometimes it might be more appropriate to define a default value for the parameter rather than checking if it was set. It can be done by adding the default keyword to the parameter:
#add_arg_table s begin
"--opt1"
"--opt2", "-o"
arg_type = Int
default = 0
"arg1"
required = true
end
aswell as the required keyword for the positional parameters, which would force the user to introduce it.

Related

What is the Julian way to combine positional, keyword, and default arguments and document them?

I am interested in a function to prompt the user for input with positional, keyword, and default arguments that is "Julian". I also want the documentation to be "Julian".
This example is what I have come up with so far:
"""
ask([prompt::String="prompt> "] [kw_prompt::String=""])::String
Prompt user for input and read and return a string from `stdin`.
If keyword argument, `kw_prompt`, is supplied, it will be the prompt.
If positional argument, `prompt`, is supplied, it will be the prompt.
If no parameter is supplied, the prompt will be "prompt> ".
# Examples
```julia_repl
julia> ask()
prompt> test
"test"
julia> ask("My prompt: ")
My prompt: test
"test"
julia> ask(kw_prompt="A long prompt >>> ")
A long prompt >>> test
"test"
```
"""
function ask(prompt::String="prompt> "; kw_prompt::String="")::String
if !isempty(kw_prompt)
print(kw_prompt)
elseif !isempty(prompt)
print(prompt)
end
return readline()
end # ask()
Any suggestions as to either the code or the documentation?
I would not call simultaneously supporting both positional and keyword args Julian. Just pick one.
If you really must, gloss over that detail in the documentation. Just chain the two together:
julia> """
ask([prompt="prompt>"])
"""
function ask(_prompt="prompt> "; prompt=_prompt)
print(prompt)
return readline()
end
ask (generic function with 2 methods)
julia> ask();
prompt>
julia> ask("foo> ");
foo>
julia> ask(prompt="bar> ");
bar>

returning result from binary search tree

I'm trying to determine if a value is found in the binary search tree.
If it's found, the value is printed. If not, a message is printed saying it wasn't found.
My problem is that even when the value is found, the message is printed saying that it wasn't found.
My result seems to reset even after returning True, and I am confused as to why this is happening... I think it's because I'm calling the function recursively, but I don't know how to fix this problem. Any help would be appreciated, thank you.
def lookUpVal(bst,val,result):
if bst == None:#base case, if the tree is 0, return none
return
elif bst['data'] == val:
print ("value found")
result = True
return result
lookUpVal(bst['left'],val,result)
lookUpVal(bst['right'],val,result)
def main(bst):
print ("Enter the value you want to find")
val = int(input())
result = 0
lookUpVal(bst,stud,result)
if result != True:
print ("Value not found")
The problem is with your result variable, you probably think you are passing by reference, what is actually happening is close to pass-by-value.
Here is an example:
def voo(x):
print('x:',id(x))
x = True
print('x:',id(x))
p = False
print('p:',id(p))
voo(p)
print('value of p:',p)
print('p:',id(p))
'id' returns a unique id for any object, including of course boolean ones.
Here's the output: (numbers will vary in your pc)
p: 1613433952
x: 1613433952
x: 1613433936
value of p: False
p: 1613433952
First note, False in output, p's value has not changed. But to see why that's happening, closely examine the id values, specially how x's id changed after assignment in function; which means python allocated a new object. And old one is still referenced by 'p', as evident in it's output, which has not changed.

Julia pass optional parameter to inner function call

I have something like the following
function test(; testvar=nothing)
# only pass testvar to function if it has a useful value
inner_function(testvar != nothing ? testvar2=testvar : # leave it out)
end
# library function, outside my control, testvar2 can't be nothing
function inner_function(; testvar2=useful value)
# do something
end
I know I can use if/else statements within test() but inner_function has lots of parameters so I would prefer to avoid that from a code duplication standpoint. Is this possible?
Note: inner_function cannot have testvar2 = nothing, if testvar2 is passed it has to have a valid value.
As #elsuizo points out, multiple dispatch is one of the core julia features which allows you to perform such operations. Find bellow a quick example:
>>> inner_func(x) = true;
>>> inner_func(::Type{Void}) = false;
Note: it seems Nothing has been renamed to Void (as a warning prompts out when I try to use it).
inner_func has 2 method definitions, if Void is passed as a parameter, the function will just return false (change this behaviour by do nothing or whatever you want to do). Instead, if the function receives anything else than Void, it will just do something else (in this case, return true).
Your test wouldn't have to perform any check at all. Just pass the parameters to the inner_func, and it will decide what to do (which of the 2 methods of the function inner_func to call) depending on the parameter type.
An example:
>>> a = [1, 2, 3, Void, 5];
>>> filter(inner_func, a)
4-element Array{Any,1}:
1
2
3
5
For the numerical elements, the function calls the method of the function that returns true, and thus, the numerical elements are returned. For the Void element, the second method of the function is called, returning false, and thus, not returning such element.

Python 3.4.1 input

When I run this script, it asks for the input. But then, it ends on the pause and doesn't prints anything. Some solution?
PS:This is Python 3.4.1
variable = input('What do you want to be?: ')
if variable is 'a unicorn' :
print ('You are now a unicorn!')
elif variable is 'a pig' :
print ('You are now a pig!')
pause = input #This is here just to pause the script
first of all you need to know the difference between is and ==
== is for value equality. Use it when you would like to know if two objects have the same value.
is is for reference equality. Use it when you would like to know if two references refer to the same object.
>>> variable = 'a unicorn'
>>> variable is 'a unicorn'
False
>>> variable == 'a unicorn'
True
just replace is with ==

How to show caller in a Julia backtrace?

Is there a way to get the file/name/line info for the caller of a Julia function?
I found this way to get some stacktrace info, and if the caller is another function (but not the main context) I get the file:line info:
module pd
global g_bTraceOn = true
export callerOfTraceIt
function callerOfTraceIt()
traceit( "hi" ) ;
end
function traceit( msg )
global g_bTraceOn
if ( g_bTraceOn )
bt = backtrace() ;
s = sprint(io->Base.show_backtrace(io, bt))
println( "debug: $s: $msg" )
end
end
end
using pd
callerOfTraceIt( )
This shows:
$ julia bt.jl
debug:
in traceit at C:\cygwin64\home\Peeter\julia\HarmonicBalance\bt.jl:15
in callerOfTraceIt at C:\cygwin64\home\Peeter\julia\HarmonicBalance\bt.jl:8
in include at boot.jl:245
in include_from_node1 at loading.jl:128
in process_options at client.jl:285
in _start at client.jl:354: hi
I'd really like just the second frame (caller of traceit()), and would also like the function name if it's available.
If you do #show bt inside traceit, you'll discover it's just a list of pointers, each corresponding to a single stack frame. Those stack frames that come from julia code (rather than C) are displayed by show_backtrace.
You can call Profile.lookup(uint(bt[1])) to extract file/function/line information from each element:
julia> Profile.lookup(uint(bt[1]))
LineInfo("rec_backtrace","/home/tim/src/julia-old/usr/bin/../lib/libjulia.so",-1,true,140293228378757)
julia> names(Profile.LineInfo)
5-element Array{Symbol,1}:
:func
:file
:line
:fromC
:ip
You likely want to ignore all elements with fromC == true.

Resources