How to display an error message in gui? - arrays

Hye guyz. I need an assistance with this. I have a figure of table. The user will insert a data into the table. If the user suddenly wrong insert the data, the table will be 'NaN'. My question is how i want to make the table does not display 'NaN' on the table but I want an error message appear. I have this coding:
function Mytable1_CreateFcn(hObject, eventdata, handles)
if isnan(Mytable1)
set(hObject, 'Data', 0);
errordlg('Input must be a number','Error');
end
handles.Mytable2 = hObject;
guidata(hObject,handles);
But there is an error with this code. Is this coding are correct to answer my question?
Update:
I did this coding on Mytable1_CellEditCallback. It still have error. Is this code true??
Mytable1=get(hObject,'Data')
if isnan(Mytable1)
set(hObject, 'Data', 0);
h=errordlg('Oh noes!','Error');
set(h, 'WindowStyle', 'modal');
uiwait(h);
return
end
handles.Mytable2 = hObject;
guidata(hObject,handles);
This is the error:
Mytable1 =
[1] [] []
[] [] []
[] [] []
[] [] []
??? Undefined function or method 'isnan' for input arguments of type 'cell'.
Error in ==> fyp_editor>Mytable1_CellEditCallback at 795
if ~isnan(Mytable1)
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> fyp_editor at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==>
#(hObject,eventdata)fyp_editor('Mytable1_CellEditCallback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uitable CellEditCallback

There are several errors in this code. Let me count the ways.
function Mytable1_CreateFcn(hObject, eventdata, handles)
The create function is executed at object creation, i.e. when the GUI is built. It is never executed otherwise, and thus it's a function you'll rarely ever want to modify. What you do want to modify is Mytable1_Callback
if isnan(Mytable1)
Mytable1 has not been defined within the function. Thus, this line will give you an error. Maybe you meant to add a line Mytable1=get(hObject,'Data')? Also, since Mytable1 is a cell array, you have to check the elements for NaNs using cellfun, i.e. write if any(cellfun(#isnan,Mytable1(:))).
set(hObject, 'Data', 0);
This line is most likely fine.
errordlg('Input must be a number','Error');
While this line is not an error, it won't behave as intended - The message pops up, but the function continues executing. Either you should write error('input must be a number), or write h=errordlg('Oh noes!');uiwait(h);return
end
Look, another line that is fine!
handles.Mytable2 = hObject; guidata(hObject,handles);
With this, you overwrite the handle to Mytable2 with the handle to Mytable1. Is that REALLY what you want?

if isnan(Mytable1)
Mytable is a cell array. Try this:
if any(isnan(cell2mat(Mytable1)))
However, there migth be an easier way, the Cell edit callback gets two inputs: the calling Object and the eventdata (and handles in guide). In the eventdata has following Fields:
Indices: 1-by-2 array containing the row and column indices of the cell the user edited.
PreviousData: Previous cell data. The default is an empty matrix, [].
EditData: User-entered string.
NewData: Value that MATLAB wrote to the Data property array. It is either the same as EditData or a converted value.
The NewData property is empty if MATLAB detects an error in the user-entered data.
Error: Error message returned if MATLAB detects an error in the user-entered data.
The Error property is empty when MATLAB successfully writes the value to the Data property.
If the Error property is not empty, then the CellEditCallback can display the string, or it can attempt to fix the problem.
Source:http://ch.mathworks.com/help/matlab/ref/uitable-properties.html#zmw57dd0e748724
With NewData or Error this should be possible to handle error checking.
for example:
MyTable_CellEditCallback(hObj,event,handles)
if isempty(event.NewData)
h=errordlg('Oh noes!','Error');
set(h, 'WindowStyle', 'modal');
uiwait(h);
return
end
% The rest of the function
end

Related

Why is my object not changing when I reassign properties in a forEach loop?

I am fetching an array of objects from an RX/JS call from an http backend. It returns an object which I am then trying to work with. I am making changes to this object using a for loop (in this example I am trying the .forEach because I have tried a number of different things and none of them seem to work.
When I run the code, I get a very weird problem. If I return the values of the properties, I get the new values (i.e. correctionQueued returns as true, etc.) but in the very next line, when I return the object, those same values are the same as the original (correctionQueued === false, etc.) HOWEVER, correctionStatus (which does not exist on the original object from http) sets just fine.
I don't understand how
array[index].correctionQueued can return true, but
array[index] returns an object with correctionQueued as false.
After the loop, the original array (checklistCopy) is identical to the object before the forEach loop, except the new property (correctionStatus) is now set, but all properties that I changed that were part of the original object remain as they were.
I have tried using a for of, for in, and .forEach. I have used the index to alter the original array, always the same result. Preexisting properties do not change, new properties are added. I have even tried working on a copy of the object in case there is something special about the object returned from rxjs, but to no avail.
checklistCopy.forEach((checklistItem, index, array) => {
if (checklistItem.crCode.isirName === correctionSetItem) {
array[index].correctionQueued = true;
array[index].correctionValue = mostRecentCorrection.correctionValue;
array[index].correctionStatus = mostRecentCorrection.status;
console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
console.log(array[index]);
}
}
);
I don't get an error, but I get..
Original object is:
correctionQueued: false;
correctionValue: JAAMES;
--
console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
true JAMES SENT
but when I print the whole object:
console.log(array[index]);
correctionQueued: false;
correctionValue: JAAMES;
correctionStatus: "SENT'; <-- This is set correctly but does not exist on original object.
console.log(array[index]) (at least in Chrome) just adds the object reference to the console. The values do not resolve until you expand it, so your console log statement is not actually capturing the values at that moment in time.
Change your console statement to: console.log(JSON.stringify(array[index])) and you should discover that the values are correct at the time the log statement runs.
The behavior you are seeing suggests that something is coming along later and changing the object properties back to the original value. Unless you show a more complete example, we can't help you find the culprit. But hopefully this answers the question about why your logs show what they show.
Your output doesn't make sense to me either but cleaning up your code may help you. Try this:
checklistCopy.forEach(checklistItem => {
checklistItem.correctionQueued = checklistItem.crCode.isirName === correctionSetItem;
if (checklistItem.correctionQueued) {
checklistItem.correctionValue = mostRecentCorrection.correctionValue;
checklistItem.correctionStatus = mostRecentCorrection.status;
console.log('checklistItem', checklistItem)
}
}
);

R: error: dimnames applied to non-array

I am trying to implement the process below with my own data. The data is in a spreadsheet with headers, and the first column has dates, the other columns have returns.
https://inovancetech.com/hmm-tutorial-1.html
My variation on the code:
Returns <- read.csv("MyData.csv",header=TRUE,stringsAsFactor=F)
Date<-as.character(Returns[,1])
DateTS<- as.POSIXlt(Date, format = "%m/%d/%Y")
TSData<-data.frame(Returns[,2:6],row.names=DateTS)
TSData<-as.xts(TSData)
MyReturns <- TSData[-1,1]
ModelData<-data.frame(MyReturns)
set.seed(1)
HMM<-depmix(MyReturns~1,data=ModelData,nstates=2,family=gaussian())
This is where I get an error:
Error in dimnames(cd) <- list(as.character(index(x)), colnames(x)) :
'dimnames' applied to non-array
I can't figure out why. Any hints?
When I ran the code I got no error. However, try this:
HMM<-depmix(list(MyReturns~1),data=ModelData,nstates=2,family=gaussian())
I got a similar error elsewhere because I was sharing the data frame variable name indirectly instead of the data itself.

Error when checking if an array element actually hold data

I have a short app that check if my music files are names to a specific routine (track number and then track name), but I'm getting an error whenever there are no files that need renaming, because the array in initialised, but the first item is nothing, null, empty (however VB refers to it).
To try and fix this, I'm running this check, but I'm still getting an error.
' Array declared like this
Dim nc_full_names(0) As String
<Code goes here to ReDim 'nc_full_names' and add the file name to the array, if a file needs renaming>
For i = 0 To UBound(nc_full_names)
'Checking if the array element actually has something in it like this
If Not nc_full_names Is Nothing Then
My.Computer.FileSystem.RenameFile(nc_full_names(i), nc_new_names(i))
Else
Exit For
End If
Next i
Here is the error that I am getting -
Argument cannont be nothing. Parameter name: file
Can anyone tell me the correct way to carry out this check?
I found that the answer was to check the first element in the array, as opposed the array itself. Thus, changing this...
If Not nc_full_names Is Nothing Then
...to this...
If Not nc_full_names(i) Is Nothing Then
...works just fine.
You can also start with a truly empty array:
Dim nc_full_names(-1) As String
Now nc_full_names.Length = 0.

How to show useful error messages from a database error callback in Phonegap?

Using Phonegap you can set a function to be called back if the whole database transaction or the individual SQL statement errors. I'd like to know how to get more information about the error.
I have one generic error-handling function, and lots of different SELECTs or INSERTs that may trigger it. How can I tell which one was at fault? It is not always obvious from the error message.
My code so far is...
function get_rows(tx) {
tx.executeSql("SELECT * FROM Blah", [], lovely_success, statement_error);
}
function add_row(tx) {
tx.executeSql("INSERT INTO Blah (1, 2, 3)", [], carry_on, statement_error);
}
function statement_error(tx, error) {
alert(error.code + ' / ' + error.message);
}
From various examples I see the error callback will be passed a transaction object and an error object. I read that .code can have the following values:
UNKNOWN_ERR = 0
DATABASE_ERR = 1
VERSION_ERR = 2
TOO_LARGE_ERR = 3
QUOTA_ERR = 4
SYNTAX_ERR = 5
CONSTRAINT_ERR = 6
TIMEOUT_ERR = 7
Are there any other properties/methods of the error object?
What are the properties/methods of the transaction object at this point?
I can't seem to find a good online reference for this. Certainly not on the Phonegap website!
http://docs.phonegap.com/en/2.2.0/cordova_storage_storage.md.html#SQLError
The SQLError object is thrown when an error occurs when manipulating a database.
This object has two properties:
code (one of your described constants)
message: A description of the error.
So in your code error.message will give you a nice description of what went wrong in which transaction.
I think that's exactly what you want, isn't it?
Best regards, F481
Transaction object
The only thing you can do with the transaction object is call its .executeSql() method, as far as I can ascertain. I cannot find any properties of this object.
Error object
The error object has a .code property which contains a number. You can either check the numerical value (see my original question above) or use something like:
if (error.code == error.DATABASE_ERR) alert('nasty database error')
The .message property is a string and may return something like this:
could not prepare statement (1 near "wibble": syntax error)
could not prepare statement (1 no such table: MyyTable)
could not prepare statement (1 table MyTable has no column named MyColunm)
could not execute statement (19 constraint failed)
Other messages are possible! This is just the few I spotted when debugging in Chrome. I notice in Phonegap the messages are briefer: "no such table: MyyTable"
There are two sets of success/error callbacks
Also note that there is another database error callback on the initial call to .transaction(). Your function will only be returned an error object (no transaction object).
The error's .code will be zero and the .message will be "the statement callback raised an exception or statement error callback did not return false".
So remember to have your statement callbacks (function mentioned inside .executeSql such as my statement_error in the code example of my original question) return true or false depending on whether you want your transaction error callback (second function mentioned inside .transaction) to be hit. The 'success' callback you specified (third one inside .transaction) will be run if you return true (or don't return anything).

Perl -- DBI selectall_arrayref when querying getting Not Hash Reference

I am very new to perl (but from a c# background) and I am trying to move some scripts to a windows box.
Due to some modules not working easily with windows I have changed the way it connects to the DB.
I have an sqlserver DB and I had a loop reading each row in a table, and then within this loop another query was sent to select different info.
I was the error where two statements can't be executed at once within the same connection.
As my connection object is global I couldn't see an easy way round this, so decided to store the first set of data in an array using:
my $query = shift;
my $aryref = $dbh->selectall_arrayref($query) || die "Could not select to array\n";
return($aryref);
(this is in a module file that is called)
I then do a foreach loop (where #$s_study is the $aryref returned above)
foreach my $r_study ( #$s_study ) {
~~~
my $surveyId=$r_study->{surveyid}; <-------error this line
~~~~
};
When I run this I get an error "Not a hash reference". I don't understand?!
Can anyone help!
Bex
You need to provide the { Slice => {} } parameter to selectall_arrayref if you want each row to be stored as a hash:
my $aryref = $dbh->selectall_arrayref($query, { Slice => {} });
By default, it returns a reference to an array containing a reference to an array for each row of data fetched.
$r_study->{surveyid} is a hashref
$r_study->[0] is an arrayref
this is your error.
You should use the second one
If you have a problem with a method, then a good first step is to read the documentation for that method. Here's a link to the documentation for selectall_arrayref. It says:
This utility method combines
"prepare", "execute" and
"fetchall_arrayref" into a single
call. It returns a reference to an
array containing a reference to an
array (or hash, see below) for each
row of data fetched.
So the default behaviour is to return a reference to an array which contains an array reference for each row. That explains your error. You're getting an array reference and you're trying to treat it as a hash reference. I'm not sure that the error could be much clearer.
There is, however, that interesting bit where it says "or hash, see below". Reading on, we find:
You may often want to fetch an array
of rows where each row is stored as a
hash. That can be done simple using:
my $emps = $dbh->selectall_arrayref(
"SELECT ename FROM emp ORDER BY ename",
{ Slice => {} }
);
foreach my $emp ( #$emps ) {
print "Employee: $emp->{ename}\n";
}
So you have two options. Either switch your code to use an array ref rather than a hash ref. Or add the "{ Slice => {} }" option to the call, which will return a hash ref.
The documentation is clear. It's well worth reading it.
When you encounter something like "Not a hash reference" or "Not an array reference" or similar you can always take Data::Dumper to just dump out your variable and you will quickly see what data you are dealing with: arrays of arrayrefs, hashes of something etc.
And concerning reading the data, this { Slice => {} } is most valuable addition.

Resources