How to avoid decreases and modify violation? - automated-tests

How I can avoid a decreases error, if my index will be not decreases after every iteration?
And why I am getting a modify clause on an object and an array, while I am using modify clause on them?
class ownerIndexs{
var oi : map<int, int>;
constructor(){
new;
}
}
class multiowned{
var m_numOwners : int;
var m_owners : array<int>;
var m_ownerIndex : ownerIndexs;
method reorganizeOwners() returns (boo : bool)
requires m_owners != null && m_ownerIndex != null
requires m_owners.Length >= 2
requires 0 <= m_numOwners < m_owners.Length
modifies this
modifies this.m_owners
modifies this.m_ownerIndex;
{
var frees : int := 1;
while (frees < m_numOwners)
decreases m_numOwners - frees //error 1
invariant m_owners != null && m_numOwners < m_owners.Length
invariant m_ownerIndex != null
{
while (frees < m_numOwners && m_owners[frees] != 0)
decreases m_numOwners - frees
invariant frees <= m_numOwners
invariant m_owners != null && m_numOwners < m_owners.Length
invariant m_ownerIndex != null
{
frees := frees +1;
}
while (m_numOwners > 1 && m_owners[m_numOwners] == 0)
invariant m_owners != null && m_numOwners < m_owners.Length
invariant m_ownerIndex != null
{
m_numOwners := m_numOwners-1;
}
if (frees < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[frees] == 0)
{
m_owners[frees] := m_owners[m_numOwners]; //error 2
m_ownerIndex.oi := m_ownerIndex.oi[m_owners[frees] := frees]; //error 3
m_owners[m_numOwners] := 0;
}
}
boo := true;
}
}
I upload this code also in Dafny, where you can compile it again: https://rise4fun.com/Dafny/bYDH .
As you can see, I modified the array m_owner and also outsourced ownerIndex to an another object, because of other modify violations issues.
But here it seems like dafnys language is limited, isn`t it?

You write modifies this.m_owners but when you go to modify this.m_owners, Dafny doesn't know that this.m_owners still refers to the same object as it did at the beginning of the method.
Try adding these invariants to your while loops,
invariant this.m_owners == old(this.m_owners)
invariant this.m_ownerIndex == old(this.m_ownerIndex)
For the decreases clause, you'll need to prove to Dafny that m_numOwners - frees actually decreases, which doesn't seem true to me - it seems to me like it could be the case that both inner while-loop conditions will be false, in which case neither m_numOwners nor frees will change. That could be a bug in your code, or maybe you need more preconditions and invariants, I'm not sure of your intent.

Related

Overloading == and !== when object is a pointer

I am new to writing operators (in this case == and !=). I have done a bit of research and so far came up with:
bool operator==(const SPECIAL_EVENT_S &rsEvent)
{
bool bSame = false;
if (rsEvent.datEvent == m_datSpecialEvent &&
rsEvent.strEvent == m_strNotes &&
rsEvent.strLocation == m_strLocation &&
rsEvent.datEventStartTime == m_datEventStartTime &&
rsEvent.datEventFinishTime == m_datEventFinishTime &&
gsl::narrow<bool>(rsEvent.bEventAllDay) == m_bEventAllDay &&
gsl::narrow<bool>(rsEvent.bSetReminder) == m_bSetReminder &&
rsEvent.iReminderUnitType == m_iReminderUnitType &&
rsEvent.iReminderInterval == m_iReminderInterval &&
rsEvent.iImageWidthPercent == m_wImageWidthPercent &&
rsEvent.strImagePath == m_strImagePath &&
rsEvent.strTextBeforeImage == m_strTextBeforeImage &&
rsEvent.strTextAfterImage == m_strTextAfterImage &&
rsEvent.eType == m_eVideoconfType &&
rsEvent.sBSSTI == m_sBSSTI)
{
// The fundamental information is unchanged
bSame = true;
}
// Now compare the MWB Event Type
if (bSame)
{
switch (rsEvent.eMWBEventType)
{
case EventTypeMWB::MWBBethelSpeakerServiceTalk:
return m_bSpecialEventBethelServiceTalk;
case EventTypeMWB::MWBVideoconferenceAssembly:
return m_bSpecialEventVideoconf && m_eVideoconfType == VideoConferenceEventType::Live;
case EventTypeMWB::MWBVideoconferenceConvention:
return m_bSpecialEventVideoconf && m_eVideoconfType == VideoConferenceEventType::Recorded;
case EventTypeMWB::MWBSpecialEvent:
return m_bSpecialEvent;
case EventTypeMWB::MWBMemorial:
return m_bEventMemorial;
case EventTypeMWB::MWBCircuitOverseerMeeting:
return m_bCircuitVisit || m_bCircuitVisitGroup;
case EventTypeMWB::MWBMeeting:
return !m_bNoMeeting;
default:
bSame = false;
}
}
return bSame;
}
bool operator!=(const SPECIAL_EVENT_S& rsEvent)
{
return !(rsEvent == *this);
}
What surprised me what when I then tried to use these operators:
if (pEntry != sEvent)
{
AfxMessageBox(_T("The special event information has changed"));
}
It does not like pEntry being a pointer. In the end I did this:
if (*pEntry != sEvent)
{
AfxMessageBox(_T("The special event information has changed"));
}
Why was this an issue in the first place? I ask that because if this was a standard function it would not matter if the object was a pointer or not.
What is the correct way to cater for this scenario?
For example:
object->Function(value)
object.Function(value)
Function can be used both by the object when it is / is not a pointer. So why not with an operator?
Function can be used both by the object when it is / is not a pointer.
Actually, no it can't. In a statement/expression like object->Function(value) the -> (member access) and () (function call) operators have the same precedence and left-to-right associativity. So, the -> is applied first and that automatically dereferences the pointer. So, the effect is the same as (*object).Function(value) – and Function is still being called on an object, rather than on a pointer.
So why not with an operator?
The syntax for calling an operator function is (or can be) rather different: because it is defined as an operator, you can call it using the operator token (between the two operands) rather than by using an explicit function call. But then, you have to pass objects, as that's what the operands are defined to be.
However, should you really want to, you can still call an operator override using explicit function-call syntax; and, in that case, you can use the -> on a pointer; like this (where operator== is effectively the 'name' of the function):
if (!pEntry->operator==(sEvent))
{
AfxMessageBox(_T("The special event information has changed"));
}
However, this seems like a lot of hard work and your *pEntry != sEvent is actually the 'correct' way to use the override.
PS: As bonus, if you're using a compiler that supports the C++20 (or later) Standard, you can add a "defaulted" operator== to your structures/classes, which would save you explicitly comparing each individual data member:
struct foo {
int a;
double b;
bool operator==(const foo&) const = default; // Compares "a" and "b"
};
struct bar {
foo f;
int c;
int d;
bool operator==(const bar&) const = default; // Compares "c", "d" and "f"
};

How can I modify an overwritten array correctly?

How can I overwrite an array, which is marked as modified, in a method?
Or is there a way in Dafny just increase the length of an array by one?
class ownerIndexs{
var oi : map<int, int>;
constructor(){
new;
}
}
class Pendingstate{
var yetNeeded : int;
var ownersDone : bv256;
var index : int;
}
class mo{
var m_pendingIndex : array<int>;
var m_ownerIndex : ownerIndexs;
var m_pending : map<int, Pendingstate>;
var m_required : int;
method confirmAndCheck(operation : int, msgsender : int) returns
(boo : bool, ownerIndex :int,pending : Pendingstate)
requires m_pendingIndex != null
modifies this.m_pendingIndex
ensures m_pendingIndex != null && pending != null
==> 0 < pending.index < m_pendingIndex.Length
&& m_pendingIndex[pending.index] == operation
{
pending := new Pendingstate;
pending.index := m_pendingIndex.Length;
this.m_pendingIndex := extendArrayByOne(this.m_pendingIndex); //Problem with modify clause
m_pendingIndex[pending.index] := operation;
}
method extendArrayByOne(oldarray:array<int>) returns (newarray:array<int>)
requires oldarray!=null
ensures newarray != null
ensures fresh(newarray)
ensures newarray.Length == oldarray.Length+1
ensures forall k::0 <= k <oldarray.Length ==> oldarray[k] == newarray[k]
modifies oldarray
{
newarray := new int[oldarray.Length+1];
var i:=0;
while (i < oldarray.Length)
invariant newarray.Length == oldarray.Length+1
invariant i<=oldarray.Length
invariant forall k::0 <= k < i ==> oldarray[k] == newarray[k]
{
newarray[i] := oldarray[i];
i := i + 1;
}
}
}
As you can see in this code.
I am trying to increase the length of an array by one in the method extendArrayByOne.
After that I am adding the element operation at the end of the new array, which was returned from extendArrayByOne, in the method confirmAndCheck.
Here is a link to a official compiler, which can compile this code:
https://rise4fun.com/Dafny/WtjA
And here is the link to my previous question about extendArrayByOne:
Modifies clause error on a changed object

Convert uintptr from reflection into pointer (*)

I just can't find the way to get a slice of pointer to each attribute of a given struct. I am using reflection to get my pointers (Thanks to https://stackoverflow.com/a/24348352/6093604)
if valueField.CanAddr() {
address = fmt.Sprintf("0x%X", valueField.Addr().Pointer())
}
As you can see, valueField.Addr().Pointer() returns a pointer addr value, however, using reflection, I would like to get a usable pointer for sql.Rows.Scan()
So what did I do is:
func StructAttributesToPointersSlice(object interface{}) []interface{} {
val := reflect.ValueOf(object)
if val.Kind() == reflect.Interface && !val.IsNil() {
elm := val.Elem()
if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr {
val = elm
}
}
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
var ptrs []interface{}
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
if valueField.Kind() == reflect.Ptr {
valueField = valueField.Elem()
}
if valueField.CanAddr() {
ptrs = append(ptrs, valueField.Addr().Pointer())
}
}
return ptrs
}
But when I try to use it for Scan() sql function:
var values []interface{}
// Iterate over each rows got from the query
for rows.Next() {
ptrs := utils.StructAttributesToPointersSlice(&newObject)
for _, item := range ptrs {
fmt.Println(reflect.TypeOf(item))
}
err = rows.Scan(ptrs...)
if err != nil {
return nil, model.Status{Code: http.StatusInternalServerError, Error: err.Error()}
} else {
values = append(values, newObject)
}
}
I am getting this error:
sql: Scan error on column index 0: destination not a pointer
I know it's because it's not the good type since it's a uintptr, but then how to transform it into usable pointer?
Thanks
Use unsafe.Pointer to convert a uintptr to a pointer of some type. As an example, the following expression converts uintptr u to a T pointer:
(*T)(unsafe.Pointer(u))
This conversion does not help in StructAttributesToPointersSlice because the struct fields can be of any type. Also, the conversion from uintptr is not needed and unsafe.
The expression valueField.Addr() is the reflect.Value for the pointer to the field. Call Interface() to get the actual pointer. To fix the program, change
ptrs = append(ptrs, valueField.Addr().Pointer())
to
ptrs = append(ptrs, valueField.Addr().Interface())
Here's a simplified version of the function:
func StructAttributesToPointersSlice(object interface{}) []interface{} {
v := reflect.ValueOf(object)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
panic("argument must be a pointer to struct")
}
v = v.Elem()
var result []interface{}
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if !f.CanSet() {
continue
}
result = append(result, f.Addr().Interface())
}
return result
}
Some notes about this code:
The argument must be a pointer to a struct.
There's no need to call CanAddr on the fields. The check for pointer to struct covers this.
The CanSet() skips over unexported fields. You may want it to panic instead.
The function panics for errors in the caller. Consider returning an error instead.
playground example

Detect blank HTML form input values

When I submit a HTML form with blank data it's still going into else block below:
String n=request.getParameter("uname");
String e=request.getParameter("mail");
String p=request.getParameter("pwd");
if(n==null || e==null || p==null)
{
// ...
} else
{
// ...
}
How can I make sure that it enters the if block?
Blank submitted input values do not arrive as null. Instead, they arrive as empty string. The null only means that the input value was not submitted at all (i.e. the input field was totally absent in the form).
If you're not interested in distinguishing the presence of a specific input field in the form, then add a String#isEmpty() check to the if block.
if (n == null || n.isEmpty() || e == null || e.isEmpty() || p == null || p.isEmpty()) {
// ...
}
You could even bake a custom utility method for this.
public static boolean isEmpty(String string) {
return (string == null || string.isEmpty());
}
if (isEmpty(n) || isEmpty(e) || isEmpty(p)) {
// ...
}
You can even go a refactoring step further with help of varargs.
public static boolean isOneEmpty(String... strings) {
for (String string : strings) {
if (string == null || string.isEmpty()) {
return true;
}
}
return false;
}
if (isOneEmpty(n, e, p)) {
// ...
}
If you would like to cover whitespace as well, then replace string.isEmpty() over all place by string.trim().isEmpty().
See also:
Our Servlets wiki page
How to determine which form has been submited and to validate them in a servlet
Validating numbers with Servlets and JSP
This is because uname,mail,pwd variables are not null instead these parameters contains empty strings.
i.e.
uname="";
mail="";
pwd="";
when you check whether these parameters are null or not , it results into false and your else block executes and persist the record into database.
you can create a method to check empty string(s).
public static boolean checkEmpty(String value){
if(!(value==null))
return value.isEmpty();
return true;
}
replace your if condition with this:
if(checkEmpty(n) || checkEmpty(e) || checkEmpty(p)){
}
String n=request.getParameter("uname");
if (n != null) n = n.trim();
if (n == null) n = "";
String e=request.getParameter("mail");
if(e != null) e = e.trim();
if(e == null) e = "";
String p=request.getParameter("pwd");
if(p != null) p = p.trim();
if(p == null) p = "";
//
// only process if values for all three exist
//
if((n.length() < 1) || (e.length() < 1) || (p.length() < 1))
{
// ...
} else
{
// ...
}

Check Cookies AND Session in Same IF Statement

I have a function that checks for Session and Cookies and redirects user based on those.
private void CheckRecruiterLogin()
{
List<string> list = new List<string>();
if (Session["Candidate"] != null ||
Request.Cookies["Candidate"] != null)
{
list = (List<string>)Session["Candidate"];
string status = list[1].ToString();
if (status.Equals("applicant") ||
Request.Cookies["Candidate"]["Status"].Equals("applicant"))
{
Response.Redirect("ApplicantHome.aspx");
}
if (status.Equals("preboarding") ||
Request.Cookies["Candidate"]["Status"].Equals("preboarding"))
{
Response.Redirect("PreboardingHome.aspx");
}
else if (status.Equals("hiring") ||
Request.Cookies["Candidate"]["Status"].Equals("hiring"))
{
Response.Redirect("HiringHome.aspx");
}
}
else if (Session["HR"] != null || Request.Cookies["HR"] != null)
{
list = (List<string>)Session["HR"];
string type = list[1].ToString();
if (type.Equals("preboarder") ||
Request.Cookies["HR"]["Type"].Equals("preboarder"))
{
Response.Redirect("PreboarderList.aspx");
}
else if (type.Equals("datamanager") ||
Request.Cookies["HR"]["Type"].Equals("datamanager"))
{
Response.Redirect("HiringList.aspx");
}
else if (type.Equals("admin") ||
Request.Cookies["HR"]["Type"].Equals("admin"))
{
Response.Redirect("AdminHome.aspx");
}
}
else if (Session["HR"] == null &&
Request.Cookies["HR"] == null)
{
Response.Redirect("index.aspx");
}
}
But the application throws a runtime exception saying Object reference not set to an instance of an object. I believe this is because there are no cookies present.
My question is: Should I separate the checking of sessions and cookies, or can I do it in one statement?
Thanks!
Your code requires both the cookie, and the session.
If this is intended, you want to change the condition to use && instead of ||.
However, it's more likely you intend the code to use session if available, and cookies if session isn't there. This is quite simply done by storing the value in a variable, and using that later:
if (Session["Candidate"] != null || Request.Cookies["Candidate"] != null)
{
var list = Session["Candidate"] as List<string>;
var status = list == null ? Request.Cookies["Candidate"]["Status"] : list[1];
if (status == "applicant")
{
...
}
...
}
That said, using cookies for security checks like this is a bad idea - they are user visible and user editable.
Also, there's no point in using Equals - just use ==. This isn't Java, .NET actually compares the value, not the reference. Although it's probably a better idea to actually do the comparison using invariant culture, case insensitive equality. There's also no point in creating new List<string> - the value is never used. Just declare the variable at the point where you already have something to fill it with.
You are directly checking that if Request has a cookie named "HR" which will throw exception if there is no cookie with this name. So you first need to check if CookieCollection have any cookie with name "HR". Here is method which checks if CookieCollection have a cookie with a given name.
if(Request.Cookies.Get("cookieNmae") !=null)
So change your if statement like this
if (Session["HR"] != null || Request.Cookies.Get("HR") !=null)

Resources