I'm getting an error:
TypeError: non-boolean (UInt16) used in boolean context
After some debugging the error is coming from this while loop.
current_value = UInt16(6)
bit = UInt16(8)
while (current_value & bit)
bit >>= 1
end
What's wrong?
After some testing it appears that while loops in Julia don't default to testing for non-zero as true. So I needed to add !=0 explicitly.
current_value = UInt16(6)
bit = UInt16(8)
while (current_value & bit != 0)
bit >>= 1
end
Related
I have tried different operators <,>,etc. Nothing seems to work when I combine comparative operators with conditional operators.
e = readline()
if e == 0
println("e is equal to 0")
else
println("e is not equal to 0")
end
The expected result is obvious, if e = 0, prints e is equal to 0, if e != 0, prints e is not equal to 0.
However, it always prints the bottom line, e is not equal to 0.
That's because readline returns a string, which is never equal to an integer (by the definition of == Julia uses).
Here are some possible ways to achieve what you want:
Compare to a string literal instead: if e == "0"
Use tryparse: if tryparse(Int, e) == 0 (will return nothing if e is not a number literal)
Use parse, but with try/catch instead of an if:
try
p = parse(Int, e)
p == 0 ? println("e is 0") : println("e is not 0")
catch
println("not even an integer.")
end
The reason that the if returns the branch that you don't expect is those given to you by #phg (you got a String by readline()).
For my code I use the following function to parse user-provided data given in a terminal:
function getUserInput(T=String,msg="")
print("$msg ")
if T == String
return readline()
else
try
return parse(T,readline())
catch
println("Sorry, I could not interpret your answer. Please try again")
getUserInput(T,msg)
end
end
end
sentence = getUserInput(String,"Which sentence do you want to be repeated?");
n = getUserInput(Int64,"How many times do you want it to be repeated?");
[println(sentence) for i in 1:n]
println("Done!")
I'm using the stopifnot function in R to validate an expected result. However, I've noticed that if the expression returns a vector of length 0, then stopifnot will not raise an error. Here is a simple reproducible example.
Imagine an optimization function where one of the list elements is named convergence containing either a 0 or 1, and I wish to validate that the element named convergence contains 0 and raise an error otherwise.
return01 <- function(x){
return(list(convergence = x))
}
opt1 <- return01(1)
I can easily do the validation I desire with stopifnot.
stopifnot(opt1$convergence == 0) # raises desired error
However, imagine I typed the wrong element name such as converged instead of convergence. My validation no longer throws any error because opt1$converged is NULL and opt1$converged == 0 resolves to logical(0)
stopifnot(opt1$converged == 0) # does not raise an error
stopifnot(NULL == 0) # does not raise an error
I've come up the workaround below where I would always have to also validate the length of the expression as well.
stopifnot(opt1$converged == 0, length(opt1$converged == 0) > 0) # raises an error
stopifnot(NULL == 0, length(NULL == 0) > 0) # raises an error
Is there a simpler, more elegant, or better practice solution here to make this validation robust to the expression returning logical(0) yet retaining the simplicity and conciseness of stopifnot(opt1$convergence == 0) rather than having to explicitly do another expression using length? Specifically, I would like the validation to also raise an error if the expression returns logical(0).
Check whether it is identical to zero:
stopifnot(identical(opt1$convergence, 0))
or if convergence is normally of integer type use 0L.
The code above will raise an error if convergence is anything other than 0. For example,
stopifnot(identical(1, 0))
## Error: identical(1, 0) is not TRUE
stopifnot(identical(NULL, 0))
## Error: identical(NULL, 0) is not TRUE
stopifnot(identical(numeric(0), 0)
## Error: identical(numeric(0), 0) is not TRUE
stopifnot(identical(logical(0), 0))
## Error: identical(logical(0), 0) is not TRUE
what is the prefered way to investigate or print out further detail (print input variable of a function, iteration number, etc.) of a failed #test inside a #testset?
I tried to wrap a try-catch-block around it. However, it doesn't seem to fire.
Here is a made-up example:
using Base.Test
rng = MersenneTwister(3231);
# define function that works different than expected
function compare(a,b)
if a == 3 && b == 3
return false
else
return a == b
end
end
# test function in a test set
#testset "Test Compare Function" begin
for iii = 1:10
number = rand(rng,1:10)
try
#test compare(number,number) == true
catch
#show(number)
end
end
end
Thank you very much!
You need to make sure it tests after the printing.
#testset "Test Compare Function" begin
for iii = 1:10
number = rand(rng,1:10)
#test begin
res = compare(number,number) == true
if !res
#show number
flush(STDOUT)
end
res
end
end
end
I'm trying to understand how to work with this package for Julia.
Im using the following code (is an example from the package):
using HttpServer
function fibonacci(n)
if n == 1 return 1 end
if n == 2 return 1 end
prev = BigInt(1)
pprev = BigInt(1)
for i=3:n
curr = prev + pprev
pprev = prev
prev = curr
end
return prev
end
http = HttpHandler() do req::Request, res::Response
m = match(r"^/fibo/(\d+)/?$",req.resource)
if m == nothing
return Response(404)
end
number = BigInt(m.captures[1])
if number < 1 || number > 100_000
return Response(500)
end
return Response(string(fibonacci(number)))
end
http.events["error"] = (client, err) -> println(err)
http.events["listen"] = (port) -> println("Listening on $port...")
server = Server(http)
run(server, 8031)
And trying to access to the server with this link:
http://localhost:8031/fibo/100
But i get the next error:
MethodError(convert,(BigInt,"100"))
ERROR: MethodError: Cannotconvert an object of type
SubString{String} to an object of type BigInt
What im doing wrong?
I have problems to figure out what r"^/fibo/(\d+)/? does, maybe there is my problem...
You get this error because method BigInt(s::AbstractString) is deprecated and was remove in julia 0.5. Use number = parse(BigInt,m.captures[1]) instead.
I have a generic function in julia that the aim is to say if a member of a vector of
a given dimension is negative or not. After a few variations I have:
function any(vec)
dim = size(vec)
for i in 1:dim[2]
fflag = vec[1,i] < 0
println("Inside any, fflag = ", fflag)
if fflag == true
result = 0
println("blabla ", result)
break
else
result =1
println("blabla ", result)
continue
end
end
println("hey, what is result? ")
println(result)
return result
end
If I run a test I found the following result:
Inside any, fflag = false
blabla 1
Inside any, fflag = false
blabla 1
Inside any, fflag = false
blabla 1
hey, what is result?
result not defined
at In[7]:57
I don't know why the compiler says me that 'result' is not defined. I know the variable exist but why does not live outside the for loop?
The documentation on variable scoping clearly states that a for loop defines a new scope. This means result is going out of scope when execution leaves the for loop. Hence it is undefined when you call println(result)
Defining result in advance of the for loop should give the behaviour you are expecting:
function any(vec)
dim = size(vec)
result = -1
for i in 1:dim[2]
...
Or if you do not wish to assign a default value, and are sure the for loop will set its value, you can do:
function any(vec)
dim = size(vec)
local result
for i in 1:dim[2]
...
In the first example, if the for loop does not set a value, result will be -1.
In the the second example, not setting a value in the for loop will leave result undefined.