z3 LastIndexOf returns wrong result? - z3

z3py's LastIndexOf is supposed to return the "last index of substring within a string". However, it seems to return the wrong results when the substring is located at the end of the string, for example:
>>> import z3
>>> def check_lastindexof(s, sub_list):
... for c in sub_list:
... z_index = z3.simplify(z3.LastIndexOf(s, c))
... v_index = s.rindex(c)
... try:
... assert z_index == v_index
... except Exception as e:
... print(f'{c: <6} FAILED expected: {v_index: >2}, got: {z_index}')
...
>>>
>>> s = 'abcdefabcdef'
>>> tests = ['a', 'abc', 'f', 'ef', 'abcdef']
>>> check_lastindexof(s, tests)
f FAILED expected: 11, got: 5
ef FAILED expected: 10, got: 4
abcdef FAILED expected: 6, got: 0
Notably, LastIndexOf returns -1 if the substring exists only once in the string, which is clearly wrong as far as I know:
>>> s = 'abcdef'
>>> check_lastindexof(s, tests)
f FAILED expected: 5, got: -1
ef FAILED expected: 4, got: -1
abcdef FAILED expected: 0, got: -1
Am I misunderstanding how z3.LastIndexOf is supposed to work or is there maybe a bug somewhere?
z3-solver version: 4.8.14.0 (installed via pip)

This looks like a bug indeed. Please report it at https://github.com/Z3Prover/z3/issues

Related

Print test fixture description in erlang eunit failure

Is there a way to print the test description of an erlang test generator that uses fixtures? Using a generator makes it tricky to tell what test is actually failing and printing the description would help out.
Example:
-module(math_test).
-include_lib("eunit/include/eunit.hrl").
-define(test(Desc, F), {Desc, {setup, fun setup/0, fun cleanup/1, F}}).
setup() ->
ok.
cleanup(_) ->
ok.
math_test_ () ->
[
?test("adds two numbers", fun add_two_numbers/0),
?test("subtract two numbers", fun subtract_two_numbers/0),
?test("undefined method called", fun undefined_error/0)
].
add_two_numbers () ->
?assertEqual(2, 1 + 3).
subtract_two_numbers () ->
?assertEqual(1, 2 - 2).
undefined_error () ->
undefined_module:uh_oh().
And then running it
[root#a7c901c022bb src]# rebar3 eunit --module=math_test
===> Verifying dependencies...
===> Compiling math
===> Performing EUnit tests...
FFF
Failures:
1) math_test:math_test_/0
Failure/Error: ?assertEqual(2, 1 + 3)
expected: 2
got: 4
%% /src/_build/test/lib/math/src/math_test.erl:20:in `math_test:-add_two_numbers/0-fun-0-/1`
Output:
Output:
2) math_test:math_test_/0
Failure/Error: ?assertEqual(1, 2 - 2)
expected: 1
got: 0
%% /src/_build/test/lib/math/src/math_test.erl:23:in `math_test:-subtract_two_numbers/0-fun-0-/1`
Output:
Output:
3) math_test:math_test_/0
Failure/Error: {error,undef,[{undefined_module,uh_oh,[],[]}]}
Output:
The first 2 errors are ok, but not great -- you can at least see in the assertion where things actually went wrong.
However the 3rd error (calling undefined module/method) is where things go horribly wrong -- there's no real way to tell where it came from!
Is there a way to improve things, like printing the test description with the failure log?
One thing you can do is putting the test description on the test itself, not the entire setup tuple. That is, change this line:
-define(test(Desc, F), {Desc, {setup, fun setup/0, fun cleanup/1, F}}).
to:
-define(test(Desc, F), {setup, fun setup/0, fun cleanup/1, {Desc, F}}).
With that change, the test descriptions are printed:
Failures:
1) math_test:math_test_/0: adds two numbers
Failure/Error: ?assertEqual(2, 1 + 3)
expected: 2
got: 4
%% /tmp/math_test/mylib/_build/test/lib/mylib/test/math_test.erl:20:in `math_test:-add_two_numbers/0-fun-0-/0`
Output:
Output:
2) math_test:math_test_/0: subtract two numbers
Failure/Error: ?assertEqual(1, 2 - 2)
expected: 1
got: 0
%% /tmp/math_test/mylib/_build/test/lib/mylib/test/math_test.erl:23:in `math_test:-subtract_two_numbers/0-fun-0-/0`
Output:
Output:
3) math_test:math_test_/0: undefined method called
Failure/Error: {error,undef,[{undefined_module,uh_oh,[],[]}]}
Output:
Another thing to try is specifying the test functions with the ?_test macro instead of as plain fun terms:
math_test_ () ->
[
?test("adds two numbers", ?_test(add_two_numbers())),
?test("subtract two numbers", ?_test(subtract_two_numbers())),
?test("undefined method called", ?_test(undefined_error()))
].
The ?_test macro remembers the line number it appeared on, and includes it in the output on test failure:
1) math_test:math_test_/0:14: adds two numbers
[...]
2) math_test:math_test_/0:15: subtract two numbers
[...]
3) math_test:math_test_/0:16: undefined method called
[...]
Now you can tell which line those tests were invoked from.
Yet another way to do it is to have the individual functions return eunit "test objects" instead of just running the tests. That would involve using ?_assertEqual instead of ?assertEqual, or wrapping the entire thing in ?_test:
math_test_ () ->
[
?test("adds two numbers", add_two_numbers()),
?test("subtract two numbers", subtract_two_numbers()),
?test("undefined method called", undefined_error())
].
add_two_numbers () ->
?_assertEqual(2, 1 + 3).
subtract_two_numbers () ->
?_assertEqual(1, 2 - 2).
undefined_error () ->
?_test(undefined_module:uh_oh())
Then the output contains both the line numbers and the names of the individual test functions:
Failures:
1) math_test:add_two_numbers/0:20: adds two numbers
Failure/Error: ?assertEqual(2, 1 + 3)
expected: 2
got: 4
%% /tmp/math_test/mylib/_build/test/lib/mylib/test/math_test.erl:20:in `math_test:-add_two_numbers/0-fun-0-/0`
Output:
Output:
2) math_test:subtract_two_numbers/0:23: subtract two numbers
Failure/Error: ?assertEqual(1, 2 - 2)
expected: 1
got: 0
%% /tmp/math_test/mylib/_build/test/lib/mylib/test/math_test.erl:23:in `math_test:-subtract_two_numbers/0-fun-0-/0`
Output:
Output:
3) math_test:undefined_error/0:26: undefined method called
Failure/Error: {error,undef,[{undefined_module,uh_oh,[],[]}]}
Output:
The answers by #legoscia are good, but I also suspect that it's the error reporting implemented by rebar3 that's suboptimal for that kind of error. Running the tests directly from eunit with its default output, you get this:
2> eunit:test(math_test).
math_test: math_test_...*failed*
in function math_test:'-add_two_numbers/0-fun-0-'/0 (math_test.erl, line 22)
**error:{assertEqual,[{module,math_test},
{line,22},
{expression,"1 + 3"},
{expected,2},
{value,4}]}
output:<<"">>
math_test: math_test_...*failed*
in function math_test:'-subtract_two_numbers/0-fun-0-'/0 (math_test.erl, line 25)
**error:{assertEqual,[{module,math_test},
{line,25},
{expression,"2 - 2"},
{expected,1},
{value,0}]}
output:<<"">>
math_test: math_test_...*failed*
in function undefined_module:uh_oh/0
called as uh_oh()
**error:undef
output:<<"">>
=======================================================
Failed: 3. Skipped: 0. Passed: 0.
With the 'verbose' option, it also prints the descriptions before each setup. Furthermore, moving the description to the test fun, and using the ?_test(...) macro to create test funs with more positional information than a plain fun, as #legoscia suggested, you get this output:
math_test:18: math_test_ (undefined method called)...*failed*
in function undefined_module:uh_oh/0
called as uh_oh()
**error:undef
output:<<"">>
You could report this to the rebar3 maintainers.

what is the named constructor equivalent of the literal constructor for the Range class?

somewhat new to rails. I am working through the exercises on 4.4.1 in Michael Hartl's learn rails tutorial and i'm a bit unclear as to what the named constructor for the class Range is
when i type the literal constructor in the console it returns the appropriate value
(1..10)
=>1..10
but when i try the named constructor
Range.new(1..10)
i receive an error
ArgumentError: wrong number of arguments (given 1, expected 2..3)
from (irb):104:in `initialize'
from (irb):104:in `new'
Ive tried adding many types of extra arguments i.e
Range.new(1)..Range.new(10)
Range.new(1)..(10)
etc..
But I'm always met with an argument error.
ArgumentError: wrong number of arguments (given 1, expected 2..3)
should be a hint that you need at least 2 parameters :
Range.new(1,10)
The 3rd parameter is to specify if the last element of the range is excluded or not :
Range.new(1,10,false).to_a
# equivalent to (1..10)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Range.new(1,10,true).to_a
# equivalent to (1...10)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]
See the documentation.
Your code
Range.new(1..10)
This is still Range#new with just one parameter : an already initialized Range!
Range.new(1)..Range.new(10)
This is a a..b syntax, so it tries to initialize a Range between a and b. What is a? Range.new(1), which isn't defined, because it only has 1 parameter. You cannot create a Range between 2 Ranges anyway :
Range.new(1,2)..Range.new(4,5)
#=> ArgumentError: bad value for range
Range.new(1)..(10)
Same problem as before. Only 1 parameter for Range.new and this would be a Range between a Range and an Integer!
You can read documentation with ri command
ri Range.new
Which prints
= Range.new
(from ruby site)
------------------------------------------------------------------------------
Range.new(begin, end, exclude_end=false) -> rng
------------------------------------------------------------------------------
Constructs a range using the given begin and end. If the exclude_end parameter
is omitted or is false, the rng will include the end object; otherwise, it
will be excluded.
NB, ri works both on the terminal commandline and inside the pry repl.

How to format TestUnit diff output

I am using MiniTest out of the box with Rails 4 and the diff output looks kind of odd, and confusing. See the following output from a failed assert_equal (assert_equal 5, someBigDecimalValue)
--- expected
+++ actual
## -1 +1 ##
-5
+#<BigDecimal:7fa7db1dd528,'0.1E2',9(18)>
The expected result specified in the test was 5, but the - character preceding it makes the expected result look like -5. The ## -1 +1 ## part is also confusing.
Output looks fine when the expected value and the actual value are of the same type:
Expected: "Foo"
Actual: "Bar"
How can I get MiniTest to output the first test something like this:
Expected: 5
Actual: #<BigDecimal:7fa7db1dd528,'0.1E2',9(18)>

value returned by cv.keywait() is not the character code

i am using opencv with python binding
want to get the value of the key pressed with the following code
cv.waitkey(10)
it gives -1 when no key is hit and this value if any of the key is hit.
-1
-1
-1
536870939
-1
-1
Could anyone help me in this please.
Thanks a lot
# While this bug remains unresolved:
if key != -1:
reactTo( key % 256 ) # Note: NOT 255
It works for me:
>>> import cv
>>> cv.NamedWindow("keypress", 0)
>>> cv.WaitKey(10000) #then I click on the new window and press the 'f' key
102
>>> chr(102)
'f'
You need to have an active window.
It seems your issue can be resolved by operating % 255 on the return value, itsa crazy bug

What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter?

In the interpreter you can just write the name of an object e.g. a list a = [1, 2, 3, u"hellö"] at the interpreter prompt like this:
>>> a
[1, 2, 3, u'hell\xf6']
or you can do:
>>> print a
[1, 2, 3, u'hell\xf6']
which seems equivalent for lists. At the moment I am working with hdf5 to manage some data and I realized that there is a difference between the two methods mentioned above. Given:
with tables.openFile("tutorial.h5", mode = "w", title = "Some Title") as h5file:
group = h5file.createGroup("/", 'node', 'Node information')
tables.table = h5file.createTable(group, 'readout', Node, "Readout example")
The output of
print h5file
differs from
>>> h5file
So I was wondering if someone could explain Python's behavioral differences in these two cases?
Typing an object into the terminal calls __repr__(), which is for a detailed representation of the object you are printing (unambiguous). When you tell something to 'print', you are calling __str__() and therefore asking for something human readable.
Alex Martelli gave a great explanation here. Other responses in the thread might also illuminate the difference.
For example, take a look at datetime objects.
>>> import datetime
>>> now = datetime.datetime.now()
Compare...
>>> now
Out: datetime.datetime(2011, 8, 18, 15, 10, 29, 827606)
to...
>>> print now
Out: 2011-08-18 15:10:29.827606
Hopefully that makes it a little more clear!
The interactive interpreter will print the result of each expression typed into it. (Since statements do not evaluate, but rather execute, this printing behavior does not apply to statements such as print itself, loops, etc.)
Proof that repr() is used by the interactive interpreter as stated by Niklas Rosenstein (using a 2.6 interpreter):
>>> class Foo:
... def __repr__(self):
... return 'repr Foo'
... def __str__(self):
... return 'str Foo'
...
>>> x = Foo()
>>> x
repr Foo
>>> print x
str Foo
So while the print statement may be unnecessary in the interactive interpreter (unless you need str and not repr), the non-interactive interpreter does not do this. Placing the above code in a file and running the file will result in nothing being printed.
The print statement always calls x.__str__() method while (only in the interactive interpeter) simply calling a variable the objects x.__repr__() method ia called.
>>> '\x02agh'
'\x02agh'
>>> print '\x02agh'
'agh'
Look at Python documentation at: http://docs.python.org/reference/datamodel.html#object.repr
object.repr(self)
Called by the repr() built-in function and by string conversions
(reverse quotes) to compute the “official” string representation of an
object. If at all possible, this should look like a valid Python
expression that could be used to recreate an object with the same
value (given an appropriate environment). If this is not possible, a
string of the form <...some useful description...> should be returned.
The return value must be a string object. If a class defines
repr() but not str(), then repr() is also used when an
“informal” string representation of instances of that class is
required.
This is typically used for debugging, so it is important that the
representation is information-rich and unambiguous.
object.str(self)
Called by the str() built-in function and by the print statement
to compute the “informal” string representation of an object. This
differs from repr() in that it does not have to be a valid Python
expression: a more convenient or concise representation may be used
instead. The return value must be a string object.
Example:
>>> class A():
... def __repr__(self): return "repr!"
... def __str__(self): return "str!"
...
>>> a = A()
>>> a
repr!
>>> print(a)
str!
>>> class B():
... def __repr__(self): return "repr!"
...
>>> class C():
... def __str__(self): return "str!"
...
>>> b = B()
>>> b
repr!
>>> print(b)
repr!
>>> c = C()
>>> c
<__main__.C object at 0x7f7162efb590>
>>> print(c)
str!
Print function prints the console every arguments __str__. Like print(str(obj)).
But in interactive console, it print function's return value's __repr__. And if __str__ not defined, __repr__ could be used instead.
Ideally, __repr__ means, we should just use that representation to reproduce that object. It shouldn't be identical between different classes, or object's that represents different values, For example, datetime.time:
But __str__ (what we get from str(obj)) should seem nice, because we show it to user.
>>> a = datetime.time(16, 42, 3)
>>> repr(a)
'datetime.time(16, 42, 3)'
>>> str(a)
'16:42:03' #We dont know what it is could be just print:
>>> print("'16:42:03'")
'16:42:03'
And, sorry for bad English :).
print(variable) equals to print(str(variable))
whereas
variable equals to print(repr(variable))
Obviously, the __repr__ and __str__ method of the object h5file produce different results.

Resources