Google Charts "Uncaught (in promise) Error: Invalid column index 3. Should be an integer in the range [0-3]." - google-visualization

Before you mark this as duplicate, note that others are asking about the error Invalid column index undefined. ... or Invalid column index 5. Should be an integer in the range [0-4]. But no. Mine is "3 should be an integer in the range of [0-3]." Also, the table does work without the formatter.format() line (just no formatting).
google.charts.load('current', {'packages':[data.chartType.toLowerCase()]});
google.charts.setOnLoadCallback(function(){
var googleData = new google.visualization.DataTable();
for (var h in data.headers) {
googleData.addColumn(data.headers[h].type, data.headers[h].html);
if (data.headers[h].format) {
var formatter = new google.visualization.NumberFormat(data.headers[h].format);
console.log(data.headers[h].format);
formatter.format(googleData, h); // Errors Here
}
}
/* ... Add Rows ... Draw Chart ... */
}
The header in question looks like this:
header[3] = {
"html": "Total Amount",
"source": "total_amount",
"type": "number",
"format": {
"negativeColor": "#F05840", //orange
"negativeParens": true,
"pattern": "#,###",
"prefix": "$",
"suffix": "",
}
}
I can't figure out why it would be erroring.
Please forgive me for any typos here, I had to hand-edit the spacing and remove my company's specific info upon pasting the code here.
Edit
WhiteHat is correct in that my h variable was a string instead of an integer, and calling parseInt did remove that error. However, instead of calling parseInt on the formatter and wherever else it's needed, I got rid of my for (var h in data.headers) calls and went with the bog-standard for (var h = 0; h < data.headers.length; h++). Although more verbose with more room for typos, it's far more standardized and predictable.
I'm still having issues with GoogleCharts NumberFormatter, but that's for another round of research and questions, not this one.

make sure you're passing a number (3),
and not a string ('3'),
by using --> parseInt...
e.g.
formatter.format(googleData, parseInt(h)); // <-- here

Related

Get Index Number of a element in the List

Iam creating a quiz App in flutter , to find whether the currect answer is selected i want to get the index number of the selected button, i doesnt know whether it is a correct approach to check the correct answer.Please help me how to get the index number when user presses the answer.
{'questionText': "What is your name",
'answers':['honest','devika','monisha','khyathy'],
'correctAnswer':'3',
},
{'questionText': "What is your Mobile Name",
'answers':['Iphone','Huawei','Applele','SAMSUNG'],
'correctAnswer':'2',
},
];
void answered(){
//find the index of the selected answer
final result = (questions[questionIndex ]['answers']indexOf());
if (result== ) {
print(result);
} `
Iam calling this List in a raised button in below code:
...(questions[questionIndex]['answers'] as List<String>).map((answer) {
return ReusableButton(
child: Text(answer),
onPressed:() =>[currentQuestion(),answered()],
color: Colors.green,
);
}).toList(),`
I think that you could just make 'correctAnswer' not the index of the answer but the answer itself, so you rather check the two string instead of checking indexes.
It should look like this.
{'questionText': "What is your name",
'answers':['honest','devika','monisha','khyathy'],
'correctAnswer':'khyathy',
},
{'questionText': "What is your Mobile Name",
'answers':['Iphone','Huawei','Applele','SAMSUNG'],
'correctAnswer':'Applele',
},
];
void answered(answer){
final result = (questions[questionIndex ]['correctAnswer']);
if (result == answer) {
print(result);
} `
I think that's right, it's my first answer in stack overflow so to all the OGs feel free to correct me.
If you want to check indexes you could use this.
{'questionText': "What is your name",
'answers':['honest','devika','monisha','khyathy'],
'correctAnswer':'3',
},
{'questionText': "What is your Mobile Name",
'answers':['Iphone','Huawei','Applele','SAMSUNG'],
'correctAnswer':'2',
},
];
void answered(answer){
final result = (questions[questionIndex ]['correctAnswer']);
final answerIndex = questions[questionIndex]['answers'].indexOf(answer).toString()
if (result == answerIndex) {
print(result);
}
...(questions[questionIndex]['answers'] as List<String>).map((answer) {
return ReusableButton(
child: Text(answer),
onPressed:() =>[currentQuestion(),answered(answer)],
color: Colors.green,
);
}).toList(),`
This should do it, I don't know what your questionIndex function does because you didn't post it so I assumed it returns an int value of the index of the current question.
Also, I don't know if you noticed but in your question, you wrote:
final result = (questions[questionIndex ]['answers']indexOf());
indexOf is a list built-in method so when you call it on a list you have to put a dot before it like so:
final result = (questions[questionIndex ]['answers'].indexOf(itemYouWantTheIndex));
There is also another error when you check the validity of the answer but I think it is just because you didn't know how to compare.
Tell me if my answer satisfied you, I'd be really happy if it did.

Flutter/Dart: How to get list value where key equals

I'm not sure why I'm having such a hard time finding an answer for this, but I have a list that I need to get the value from where the key matches certain criteria. The keys are all unique. In the example below, I want to get the color where the name equals "headache". Result should be "4294930176".
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
Error I get: Class '_InternalLinkedHashMap' has no instance getter 'name'. Any suggestions?
EDIT:
Here's how I'm adding the data to the list, where userDocuments is taken from a Firestore collection:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
I guess, I got what the problem was. You were making a little mistake, and that was, you're trying to call the Map element as an object value.
A HashMap element cannot be called as f.name, it has to be called f['name']. So taking your code as a reference, do this, and you are good to go.
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
Check that out, and let me know if that helps you, I am sure it will :)

Apps Scirpt and regex. How?

I am using .indexOf() to parse an array in a separate sheet via url and find a string in a header to return a numerical value or -1. Issue is I need to find the string match that is non case sensitive. ie var targetEmail = targetHeader.indexOf("Email"); would need to match "email", "user email", User email", etc. Normally I would use a regex but can't find a way to do this in Apps Script. Please any help would be very much appreciated.
sample code below:
var userHeader = USER.getRange(1, 1, 1, USER.getLastColumn()).getValues()[0];
var targetHeader = importSheet.getRange(1, 1, 1, importSheet.getLastColumn()).getValues()[0];
var ui = SpreadsheetApp.getUi();
var targetEmail = targetHeader.indexOf("Email");
if(targetEmail == -1)
ui.alert("Can not find Email column. Please rename column in source sheet.");
Using Javascript RegExp, you can use the following
let targetEmail = targetHeader.findIndex(h => /email/gi.test(h));
if(targetEmail == -1)
ui.alert("Can not find Email column. Please rename column in source sheet.");
Note: findIndex, let and the function shorthand will only work if your script is using the new V8 runtime.
I personally prefer to name the column I want using Google Sheets named ranges, and then use getNamedRanges(), so I'll be able to find the column number by its range name, regardless of the column heading text. If columns are inserted or deleted, the named range still points to the column you're looking for.
You could solve for this by
(1) joining the array into a string
targetHeader.join()
(2) and then changing the string to lowercase
toLowerCase()
and then looking for "email" (lower case).
var targetHeader = importSheet.getRange(1, 1, 1, importSheet.getLastColumn()).getValues()[0];
targetHeader = targetHeader.join().toLowerCase();
var targetEmail = targetHeader.indexOf('email');
Edit:
To find the column number with the word 'email' in it:
var importSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet101');
var targetHeader = importSheet.getRange(1, 1, 1, importSheet.getLastColumn()).getValues()[0];
var flag = false;
for (var c = 0; c < targetHeader.length; c++) {
var cellValue = targetHeader[c].toLowerCase();
if (cellValue.indexOf('email') > -1) {
flag = true;
break;
}
}
if (!flag) {
// ui alert that email not found
} else {
var columnWithEmalInHeader = c + 1;
// column with value 'email' found. Column number is c+1
// first time match of 'email' will pop-up here. All subsequent amounts will be ignored.
}

Google Script .getvalue() Not Working With Cells With a Formula In It

I have this google script for google sheets that moves rows of data from "Sheet1" to "Sheet2" when column 15 says "tracking", and it works perfectly fine when I type in "tracking" but I would like that column to be an IF equation something like IF(G:G="tracking not available at this time","","tracking"). But the code does not seem to recognize the formula change from "" to "tracking". Do I need to change the getvalue()? Or is there a different workaround to this issue? I've used =query(importrange) withing the spreadsheet to copy over data with a trigger word, but I really want this to be more of an archive system and add a row to the bottom of "Sheet2" whenever row15 on "sheet1"Thanks! Here is the code:
function onEdit(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(s.getName() == "Sheet1" && r.getColumn() == 14 && r.getValue() == "tracking") {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Sheet2");
if(targetSheet.getLastRow() == targetSheet.getMaxRows()) {
targetSheet.insertRowsAfter(targetSheet.getLastRow(), 20);
}
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).moveTo(target);
s.deleteRow(row);
}
}
I had an issue with this recently
I spent about 3 hours debugging something yesterday and this was the culprit.
try using r.getDisplayValue() instead of r.getValue
I am still new to this myself, and feel free to correct me if I am wrong, because if there is a different reason I would really love to know!!!
It seems that if a value in a cell is not typed in but placed there through a formula such as =query() or a similar method, I don't think it actually sees that there is a value in the cell. (I got null values or the formula itself)
If you use getDisplayValue, it "should" get the value that you actually see in the cell.
The correct way to get formulas, instead of displayed values, is with getFormulas rather than getValues

Map/reduce to get the count and latest date for each document grouped by key

A simple version of my document document is the following structure:
doc:
{
"date": "2014-04-16T17:13:00",
"key": "de5cefc56ff51c33351459b88d42ca9f828445c0",
}
I would like to group my document by key, to get the latest date and the number of documents for each key, something like
{ "Last": "2014-04-16T16:00:00", "Count": 10 }
My idea is to to do a map/reduce view and query setting group to true.
This is what I have so far tried. I get the exact count, but not the correct dates.
map
function (doc, meta) {
if(doc.type =="doc")
emit(doc.key, doc.date);
}
reduce
function(key, values, rereduce) {
var result = {
Last: 0,
Count: 0
};
if (rereduce) {
for (var i = 0; i < values.length; i++) {
result.Count += values[i].Count;
result.Last = values[i].Last;
}
} else {
result.Count = values.length;
result.Last = values[0]
}
return result;
}
You're not comparing dates... Couchbase sorts values by key. In your situation it will not sort it by date, so you should do it manually in your reduce function. Probably it will look like:
result.Last = values[i].Last > result.Last ? values[i].Last : result.Last;
and in reduce function it also can be an array, so I don't think that your reduce function always be correct.
Here is an example of my reduce function that filter documents and leave just one that have the newest date. May be it will be helpful or you can try to use it (seems it looks like reduce function that you want, you just need to add count somewhere).
function(k,v,r){
if (r){
if (v.length > 1){
var m = v[0].Date;
var mid = 0;
for (var i=1;i<v.length;i++){
if (v[i].Date > m){
m = v[i].Date;
mid = i;
}
}
return v[mid];
}
else {
return v[0] || v;
}
}
if (v.length > 1){
var m = v[0].Date;
var mid = 0;
for (var i=1;i<v.length;i++){
if (v[i].Date > m){
m = v[i].Date;
mid = i;
}
}
return v[mid];
}
else {
return v[0] || v;
}
}
UPD: Here is an example of what that reduce do:
Input date (values) for that function will look like (I've used just numbers instead of text date to make it shorter):
[{Date:1},{Date:3},{Date:8},{Date:2},{Date:4},{Date:7},{Date:5}]
On the first step rereduce will be false, so we need to find the biggest date in array, and it will return
Object {Date: 8}.
Note, that this function can be called one time, but it can be called on several servers in cluster or on several branches of b-tree inside one couchbase instance.
Then on next step (if there were several machines in cluster or "branches") rereduce will be called and rereduce var will be set to true
Incoming data will be:
[{Date:8},{Date:10},{Date:3}], where {Date:8} came from reduce from one server(or branch), and other dates came from another server(or branch).
So we need to do exactly the same on that new values to find the biggest one.
Answering your question from comments: I don't remember why I used same code for reduce and rereduce, because it was long time ago (when couchbase 2.0 was in dev preview). May be couchbase had some bugs or I just tried to understand how rereduce works. But I remember that without that if (r) {..} it not worked at that time.
You can try to place return v; code in different parts of my or your reduce function to see what it returns on each reduce phase. It's better to try once by yourself to understand what actually happens there.
I forget to mention that I have many documents for the same key. In fact for each key I can have many documents( message here):
{
"date": "2014-04-16T17:13:00",
"key": "de5cefc56ff51c33351459b88d42ca9f828445c0",
"message": "message1",
}
{
"date": "2014-04-16T15:22:00",
"key": "de5cefc56ff51c33351459b88d42ca9f828445c0",
"message": "message2",
}
Another way to deal with the problem is to do it in the map function:
function (doc, meta) {
var count = 0;
var last =''
if(doc.type =="doc"){
for (k in doc.message){
count += 1;
last = doc.date> last?doc.date:last;
}
emit(doc.key,{'Count':count,'Last': last});
}
}
I found this simpler and it do the job in my case.