Subscript out of range: '[number: 1]' while using jqPlot - javascript

Working with some legacy speghatti code with very limited knowledge.
There are two different charts jqPlot . First chart represnts Total number of countries in each YearMonth. Second chart would represent all the country name and there distinct number. For 2nd Chart the number of each country will always be 1, however the countries themselves will be one or more.
1st chart (as above) is generated correctly and selecting one BAR from the chart query returns correct name for the countries. But problem occurs while plotting the second chart. Gives error. What am I missing?
ERROR : Subscript out of range: '[number: 1]'
The following piece of code creates JSON through an AJAX call a nd sends to the Jquery function to create a Chart.
' Create categories
cat="["
for i = 0 to recCount
if i<>0 then cat=cat&"," end if
cat=cat&""""&data(0,i)&""""
next
cat = cat & "]"
DebugWrite("jsonCat:" & cat)
startYear= ymStart \ 100
startMonth=ymStart mod 100
periodMonths=25
json="[["
y=startYear
m=startMonth
for i=0 to recCount
DebugWrite("recCount:" & recCount)
if i<>0 then json=json&"," end if ' separator for all but first
json=json&"["&i+1
if data(1,i)<>0 then ' check if there are records to prevent / 0
json=json&","& data(1,i)&","""&data(1,i)&""","""&data(0,i)&"""]" '<<<<<THIS LINE CREATING PROBLEM>>>>>>>>>
else
json=json&",0,""n=0""]" ' put empty json data if no records
end if
next
json=json&"]]"
' clear data array, information now in JSON
set data = nothing
The query for the DATA is as follows:
detLevel="Country"
sqlWhere="1=1"
strSQL = "SELECT "&detLevel&" from"&_
" (SELECT "&detLevel&",COUNT(Distinct c.Country) as CountryCount"&_
" FROM BIDashboard.dbo.ISO c"&_
" WHERE ym is not null AND ym="&ym&_
" AND "&sqlWhere&" GROUP BY "&detLevel&") as x"&_
" WHERE "&detLevel&" IN (SELECT DISTINCT "&detLevel&" FROM dbo.ISO)"&_
" ORDER BY 1"

Related

Is there a way to insert a large amount of data in one sql statement? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is the database query faster if I insert multiple rows at once:
like
INSERT....
UNION
INSERT....
UNION
(I need to insert like 2-3000 rows)
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Source
If you have your data in a text-file, you can use LOAD DATA INFILE.
When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.
Optimizing INSERT Statements
You can find more tips on how to speed up your insert statements on the link above.
Just use a SELECT statement to get the values for many lines of the chosen columns and put these values into columns of another table in one go. As an example, columns "size" and "price" of the two tables "test_b" and "test_c" get filled with the columns "size" and "price" of table "test_a".
BEGIN;
INSERT INTO test_b (size, price)
SELECT size, price
FROM test_a;
INSERT INTO test_c (size, price)
SELECT size, price
FROM test_a;
COMMIT;
The code is embedded in BEGIN and COMMIT to run it only when both statements have worked, else the whole run up to that point gets withdrawn.
Here is a PHP solution ready for use with a n:m (many-to-many relationship) table :
// get data
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
// prepare first part of the query (before values)
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
//loop the table 1 to get all foreign keys and put it in array
foreach($table_1 as $row) {
$query_values[] = "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW())";
}
// Implode the query values array with a coma and execute the query.
$db->query($query . implode(',',$query_values));
EDIT : After #john's comment I decided to enhance this answer with a more efficient solution :
divides the query to multiple smaller queries
use rtrim() to delete last coma instead of implod()
// limit of query size (lines inserted per query)
$query_values = "";
$limit = 100;
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
foreach($table_1 as $row) {
$query_values .= "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW()),";
// entire table parsed or lines limit reached :
// -> execute and purge query_values
if($i === array_key_last($table_1)
|| fmod(++$i / $limit) == 0) {
$db->query($query . rtrim($query_values, ','));
$query_values = "";
}
}
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";

Google Sheets - Script to Generate Paragraph in a Column

I've found a LOT of scripts that will take data from a Google Sheet and create a Google Doc, but I need a paragraph (really just a few sentences) generated into the Sheet itself. We create web pages for people who enter their information into a Google Form (name of their store, location, brands carried, etc.), we do this by exporting the Google Sheet into a .csv file, and uploading the file which generates the pages. So we need the paragraph to be in the Google Sheet.
I need a script that will give me a paragraph that says:
Column D is a "OUR BRAND" dealer located in Column H. Column D also sells Column T.
I've been trying to figure out this script for hours piecing together what I've found elsewhere and it seems like every time I sort out one bit, I screw up another bit. It's a mess:
function onEdit() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = activeSheet.getSheetByName("All Dealers");
var cell = sheet.getActiveCell();
var row = cell.getRow();
var col = cell.getColumn();
// Fetch the range of cells
var dataRange = sheet.getRange(row, col)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var dealerName = row[0]
var city = row[1]
var brand = row[2];
}
var body = 'dealerName' + "is a OURBRAND located in" + 'city' + 'dealerName' + "also sells" + 'brand';
SpreadsheetApp.getActiveSheet().getRange("AI"+row).setValue('body');
}
Spreadsheet is available here
You don't need a script for this: an arrayformula can do what you want.
Preliminary version: in cell AI2, enter
=arrayformula(D2:D & " is a BRAND dealer located in " & H2:H & ". " & D2:D & " also sells " & T2:T)
(Note that I've put spaces in appropriate places; this is something that requires extra attention when concatenating strings.)
The drawback of the above is that you also get some text in empty rows. To filter them out, replace each column reference by its filtered version: filter( ... , len(D2:D)) keeps only the rows with nonempty column D.
=arrayformula(filter(D2:D, len(D2:D)) & " is a BRAND dealer located in " & filter(H2:H, len(D2:D)) & ". " & filter(D2:D, len(D2:D)) & " also sells " & filter(T2:T, len(D2:D)))
This being in arrayformula means that as new data is added to columnds D,H,T, new text will be created in column AI.

WebSQL: Error processing SQL: number of '?'s in statement string does not match argument count

I want to create a dynamic function to INSERT data into the webSQL Database. I cannot use indexed DB because Zetakey does not support it.
tx.executeSql("INSERT INTO " + table + "(" + formatfields + ")
VALUES (" + formatqm + ")",
[formatvalues],
webdb.onSuccess,
webdb.onError);
Ich übergebe an den Query:
formatfields = "one, two"; (up to an undefined number)
formatqm = "?, ?";
formatvalues = "123, 456"; (dynamic user entries for x fields)
Can someone tell me what do I have to do with the formatvalues? When I write 123, 456 directly its working fine.
Thanks in advance!
Instead of dynamically create or change table column fields, use JSON serialization of the record. Basically store stringify user given object data on INSERT and parse on retrieval. If you need query over column, initialize those columns only. It will be just like IndexedDB does.
/*array.push */
formatvalues = new Array;
formatvalues.push("123");
and so on!

Modify JavaScript Object and use setRowsData to write to individual cell

I am using getRowsData to retrieve the information, but I would like to modify the values stored within a JS object and then write that modified value back into the cell. I would like to use the normalized header variable that was created with getRowsData to write back into the cell. So if I retrive the info using
var thirdEmployee = employeeObjects[2];
var stringToDisplay = "The third column is: " + thirdEmployee.firstName + " " + thirdEmployee.lastName;
stringToDisplay += " (id #" + thirdEmployee.employeeId + ") working in the ";
stringToDisplay += thirdEmployee.department + " department and with phone number ";
stringToDisplay += thirdEmployee.phoneNumber;
ss.msgBox(stringToDisplay);
Then, for example, I would assign a new value to the Javascript object thirdEmployee.phoneNumber; and then have it written into the proper location in the range (i.e., active row, column # based on header).
thirdEmployee.phoneNumber = "123-555-5555";
thirdEmployee.phoneNumber.setNewValue();
or
setNewValue.thirdEmployee.phoneNumber;
Basically, it would be a modified version of setRowsData but allow for modification of one object and then telling that object to be written into the spreadsheet based on the active row & column based on the header.
Anyone use or know how to do this?
The setRowsData() helper function from the Writing Data from JavaScript Objects to a Spreadsheet tutorial already supports the ability to write a single object. To use it, though, you need to provide both of the optional parameters optHeadersRange and optFirstDataRowIndex.
If we assume that your headers are in row 1, here's how you could update thirdEmployee:
var headersRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var thirdEmployee = employeeObjects[2];
...
thirdEmployee.phoneNumber = "123-555-5555";
setRowsData(sheet, [thirdEmployee], headersRange, 3 );

Display value markers in Google Charts BarChart (JavaScript API)

I'm trying to render a Google Charts BarChart with the value labels on, or next to the bars. By default, the values are being shown when the user hovers over a bar. I would like to show these values permanently in the graph.
As far as I can see, this was possible using the Image Charts API, but not with the JavaScript API. I am missing something?
Why not add the values in the legend (its how i got around the same problem)
Where you are setting the name of each column add the value next to it.
For example keeping track of stock in a warehouse:
var sold = 300;
var missing = 7;
var reserved = 5;
var available = 143;
var data = google.visualization.arrayToDataTable([
[' Available (' + available + ')', 'Missing (' + missing+ ')', 'Reserved (' + reserved+ ')', 'Sold (' + sold+ ')'],
[available, missing, reserved, sold]
]);
Output:
Available (143)
Missing (7)
Reserved (5)
Sold (300)

Categories