Hi I am trying to push data from my array of queries into excel but only the header seems to be displayed but the results are being pushed. When I did a console.log to see whether they would be pushed it says undefined. Any ideas as to why?
Example code:
var excel_data=[];
excel_data.push=(['Source', 'Count of thing 1', 'Count of thing 2', 'Count of thing 3']);
var database = new database(config);
var query_array = ['select count(*) as count_of_thing1 from table1', 'select count(*) as count_of_thing2 from table2', 'select count(*) as count_of_thing3 from table3'];
query_array.forEach(q => {
database.query(q)
.then(rows => {
_.each(rows, function(row){
excel_data.push([row.count_of_thing1, row.count_of_thing2, row.count_of_thing3]);
});
})
var wb = XLSX.utils.book_new();
var ws_name = "Query_Results";
var wscols = [ {width: 15} ];
var wsrows = [];
var ws = XLSX.utils.aoa_to_sheet(excel_data, {cellDates:true});
ws['!cols'] = wscols;
ws['!rows'] = wsrows;
XLSX.utils.book_append_sheet(wb, ws, ws_name);
var filenames = [
['mysql.xlsx', {bookSST:true}],
['mysql.csv', {bookSST:true}],
];
filenames.forEach(function(r) {
XLSX.writeFile(wb, r[0], r[1]);
XLSX.readFile(r[0]);
});
});
Related
I'm having an issue with dates and I've been unable to find any solutions online. I've created a google sheet with a modal form to collect fleet vehicle driver info; name, dob, oln, etc., with several other date fields. The entire spreadsheet is formatted as plain text and the input types on the associated HTML pages are also text (if I format any of the date-related cells on the sheet as a date, my form won't open when I run the app script code).
When I open the form and edit a driver, the information presented is what I expect. However, if I save the record, the dob (date of birth) field in the underlying sheet turns from a date to #NUM!; surprisingly, the other date fields are not changed.
I made a copy of the spreadsheet with some dummy info, which can be viewed at https://docs.google.com/spreadsheets/d/1_trLFDh1SoIXJnmRz73ludTaT64qgXd8qJKMC6grueU/edit#gid=0
Published link is https://docs.google.com/spreadsheets/d/e/2PACX-1vSzyRgN6i0RJRjcUKxcNlnuQC0P1ZHlhPPuy19G9q-sp0XQfuMjiDWvHMnWA3_HT_QSTQEDYMgrUezV/pubhtml
Code for pulling data in from spreadsheet. Code is in ServerSideFuncs.gs
function editCustomerById(id, customerInfo){ const ss = SpreadsheetApp.getActiveSpreadsheet(); const ws = ss.getSheetByName("Drivers"); const custIds = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues().map(r => r[0].toString().toLowerCase()); const
posIndex = custIds.indexOf(id.toString().toLowerCase()); const rowNumber = posIndex === -1 ? 0 : posIndex + 2; ws.getRange(rowNumber, 2, 1, 20).setValues([[ customerInfo.firstName, customerInfo.middleName, customerInfo.lastName, +customerInfo.birthDate,
customerInfo.driverClassification, customerInfo.email, customerInfo.cellPhone, customerInfo.active, customerInfo.dpaa, customerInfo.driversLicense, customerInfo.dlState, customerInfo.deptOrg, customerInfo.dateSubmitted, customerInfo.dateReceived, customerInfo.dateExpires,
customerInfo.accepted, customerInfo.certDate, customerInfo.certClassification, customerInfo.notified, customerInfo.standing ]]); return true; }
Code from main.html
function afterEditViewLoads(params){ loadingStart(); document.getElementById("customer-id").value = params.custID; google.script.run.withSuccessHandler(function(customerInfo){ document.getElementById("first-name").value = customerInfo.firstName; document.getElementById("middle-name").value
= customerInfo.middleName; document.getElementById("last-name").value = customerInfo.lastName; document.getElementById("birth-date").value = customerInfo.birthDate; document.getElementById("driver-classification").value = customerInfo.driverClassification;
document.getElementById("email").value = customerInfo.email; document.getElementById("cell-phone").value = customerInfo.cellPhone; document.getElementById("active").value = customerInfo.active; document.getElementById("dpaa").value = customerInfo.dpaa;
document.getElementById("drivers-license").value = customerInfo.driversLicense; document.getElementById("dl-state").value = customerInfo.dlState; document.getElementById("deptOrg").value = customerInfo.deptOrg; document.getElementById("date-submit").value
= customerInfo.dateSubmitted; document.getElementById("date-received").value = customerInfo.dateReceived; document.getElementById("accepted").value = customerInfo.accepted; document.getElementById("date-expires").value = customerInfo.dateExpires; document.getElementById("cert-date").value
= customerInfo.certDate; document.getElementById("cert-classification").value = customerInfo.certClassification; document.getElementById("notified").value = customerInfo.notified; document.getElementById("standing").value = customerInfo.standing; loadingEnd();
}).getCustomerById(params.custID); } function editCustomer(){ loadingStart(); var customerInfo = {}; customerInfo.firstName = document.getElementById("first-name").value; customerInfo.middleName = document.getElementById("middle-name").value; customerInfo.lastName
= document.getElementById("last-name").value; customerInfo.birthDate = document.getElementById("birth-date").value; customerInfo.driverClassification = document.getElementById("driver-classification").value; customerInfo.email = document.getElementById("email").value;
customerInfo.cellPhone = document.getElementById("cell-phone").value; customerInfo.active = document.getElementById("active").value; customerInfo.dpaa = document.getElementById("dpaa").value; customerInfo.driversLicense = document.getElementById("drivers-license").value;
customerInfo.dlState = document.getElementById("dl-state").value; customerInfo.deptOrg = document.getElementById("deptOrg").value; customerInfo.dateSubmitted = document.getElementById("date-submit").value; customerInfo.dateReceived = document.getElementById("date-received").value;
customerInfo.dateExpires = document.getElementById("date-expires").value; customerInfo.accepted = document.getElementById("accepted").value; customerInfo.certDate = document.getElementById("cert-date").value; customerInfo.certClassification = document.getElementById("cert-classification").value;
customerInfo.notified = document.getElementById("notified").value; customerInfo.standing = document.getElementById("standing").value; var id = document.getElementById("customer-id").value; google.script.run.withSuccessHandler(function(res){ document.getElementById("save-success-message").classList.remove("invisible");
loadingEnd(); setTimeout(function(){ document.getElementById("save-success-message").classList.add("invisible"); },2000); }).editCustomerById(id,customerInfo); }
partial Code from editcustomer.html
<div class="col-md-auto">
<label for="birth-date" class="form-label">DOB</label>
<input type="text" class="form-control" id="birth-date" placeholder="Birthday">
</div>
function editCustomerById(id, customerInfo) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Drivers");
const custIds = ws.getRange(2, 1, ws.getLastRow() - 1, 1).getValues().map(r => r[0].toString().toLowerCase());
const posIndex = custIds.indexOf(id.toString().toLowerCase());
const rowNumber = posIndex === -1 ? 0 : posIndex + 2;
ws.getRange(rowNumber, 2, 1, 20).setValues([
[
customerInfo.firstName,
customerInfo.middleName,
customerInfo.lastName,
+customerInfo.birthDate, // <------------ I think the trouble is here
customerInfo.driverClassification,
customerInfo.email,
customerInfo.cellPhone,
customerInfo.active,
customerInfo.dpaa,
customerInfo.driversLicense,
customerInfo.dlState,
customerInfo.deptOrg,
customerInfo.dateSubmitted,
customerInfo.dateReceived,
customerInfo.dateExpires,
customerInfo.accepted,
customerInfo.certDate,
customerInfo.certClassification,
customerInfo.notified,
customerInfo.standing
]
]);
return true;
}
Reference
Unary plus (+)
I want to update values in my Data.json file.
{
"A0_Water":"-306.3",
"A1_Water":"0.0",
"A2_Water":"0.0",
"A3_Water":"0.0",
"Barometer":"100.8",
"Bar_Offset":"0",
"Temp":"29.95",
"ip":"192.168.2.47",
"serial":"02:42:52:bf:82:27",
"A0_Sensor":"PS30A",
"A1_Sensor":"None",
"A2_Sensor":"None",
"A3_Sensor":"None",
"A0_Offset":"0",
"A1_Offset":"0",
"A2_Offset":"0",
"A3_Offset":"0"
}
The code that I have working:
I am currently not using var data object to update the Data.json file
var data = {
'A0_Water': c_inh2o_A0,
'A1_Water': c_inh2o_A1,
'A2_Water': c_inh2o_A2,
'A3_Water': c_inh2o_A3,
'Barometer': b_mbar_corrected,
'Temp': b_temp
};
var fileName = '/home/admin/reactwatertracker/src/var/Data.json';
var file4 = require(fileName);
var file5 = file4;
var file6 = file4;
var file7 = file4;
var file8 = file4;
var file9 = file4;
file4['A0_Water'] = c_inh2o_A0;
file5['A1_Water'] = c_inh2o_A1;
file6['A2_Water'] = c_inh2o_A2;
file7['A3_Water'] = c_inh2o_A3;
file8['Temp'] = b_temp;
file9['Barometer'] = b_mbar_corrected;
console.log('Writing to' + fileName);
fs.writeFile(fileName, JSON.stringify(file4,file5,file6,file7,file8,file9, null, 2), function (err) {
if (err) return console.log(err);
console.log (JSON.stringify(file4));
});
I cannot seem to get this script to work for 'statistics':
function searchByKeyword2() {
var results = YouTube.Search.list('statistics', {q: 'dogs', maxResults: 5, });
for(var i in results.items) {
var item = results.items[i];
Logger.log(item);
}
}
I can use 'id', 'snippet', or 'id, snippet', but I cannot get it to work with 'statistics'. I've been looking an answer for hours, but I haven't found anything. Any clues?
Per the API documentation, YouTube.Search includes results for Videos, Channels, and Playlists. Not all of these resources have statistics nodes, and thus the YouTube.Search endpoint does not allow querying for the statistics node - only id and snippet.
For collections which track statistics, like Videos, you query them directly to access statistics. Since Videos.list does not search, you need to first search and then provide the relevant video IDs. Note that you can change the search order (and many other search properties) - full details available in the API reference - but the default sort is 'relevance'.
As an example:
function getVideoStatistics(videoIds) {
const options = {
id: videoIds.join(","),
fields: "nextPageToken,items(id,statistics)"
};
const results = [];
do {
var search = YouTube.Videos.list('statistics', options);
if (search.items && search.items.length)
Array.prototype.push.apply(results, search.items);
options.pageToken = search.nextPageToken;
} while (options.pageToken);
return results;
}
function getVideosFromQuery(query, maxResults) {
const options = {
q: query,
maxResults: maxResults,
type: 'video',
fields: "nextPageToken,pageInfo/totalResults,items(id/videoId,snippet(title,channelTitle))"
};
const results = [];
do {
var search = YouTube.Search.list('snippet', options);
if (search.items && search.items.length)
Array.prototype.push.apply(results, search.items);
options.pageToken = search.nextPageToken;
} while (options.pageToken && results.length < search.pageInfo.totalResults && results.length < maxResults);
return results;
}
function foo() {
var someQuery = "something";
var searchResults = getVideosFromQuery(someQuery, 50);
var ids = searchResults.map(function (videoSearchResult) {
return videoSearchResult.id.videoId;
});
var stats = getVideoStatistics(ids);
console.log({message:"query video statistics", searchResults: searchResults, statistics: stats});
}
I have the following (mostly) working script using the Admin Directory API. However, rather than pulling the entire domain - I would like to just pull the information for a specific department.
function listAllUsers() {
var ss = SpreadsheetApp.getActive();
var pageToken, page, count = 0;
var listArray = [];
listArray.push(['full name', 'first name', 'last name', 'email', 'department', 'ID'])
do {
page = AdminDirectory.Users.list({
domain: 'example.co.uk',
orderBy: 'givenName',
maxResults: 100,
pageToken: pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, user.organizations, user.id,]);
}
}
pageToken = page.nextPageToken;
break; // This means you only get one page
} while (pageToken);
try {
var outputSheet = ss.getSheetByName('allMembers');
outputSheet.getDataRange();
} catch(err) {
var outputSheet = ss.insertSheet('allMembers', 2);
}
outputSheet.getDataRange().clear();
outputSheet.getRange(1, 1, listArray.length, listArray[0].length).setValues(listArray);
outputSheet.getRange(1, 6, outputSheet.getLastRow(), 4).setHorizontalAlignment("center");
outputSheet.getRange(1, 1, outputSheet.getLastRow(), 1).setHorizontalAlignment("center");
var width = [150, 150, 180, 250, 250, 200];
formatSheet(outputSheet, width);
}
I have tried to filter to the domain by using user.organization[].domain but just got error messages. I changed the parameter user.organizations to user.organizations[].department as documented in the Admin SDK reference.
This initially threw out a SyntaxError, and when changed to user.organizations[0].department it threw out the error message:
TypeError: Cannot read property "0" from undefined
I omitted the brackets altogether and used user.organizations.department, but got:
TypeError: Cannot read property "department" from undefined
Also, if possible I would like to list the Department and Title separably. Currently, it exports the information in this format:
{customType=work, name=, location=002, title=Technical Support Manager, department=Technical Support, primary=true}
The current display:
My desired output format:
You are getting those errors because some of the users in your domain don't have the department/ title user property.
Adding 2 variable and try.. catch blocks should allow the code to work as you expect.
Here is the updated code:
function listAllUsers() {
var ss = SpreadsheetApp.getActive();
var pageToken,
page,
count = 0;
var listArray = [];
listArray.push(['full name', 'first name', 'last name', 'email', 'department', 'title', 'ID'])
do {
page = AdminDirectory.Users.list({
domain : 'example.com',
orderBy : 'givenName',
pageToken : pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
var department,
title; // Addded two new variables
try { // Try to get the users department if there is an error push the error to the array
department = user.organizations[0].department;
} catch (e) {
department = e
}
try {// Try to get the users title if there is an error push the error to the array
title = user.organizations[0].title;
} catch (e) {
title = e
}
listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, department, title, user.id, ]);
}
}
pageToken = page.nextPageToken;
break; // This means you only get one page
} while (pageToken);
try {
var outputSheet = ss.getSheetByName('allMembers');
outputSheet.getDataRange();
} catch (err) {
var outputSheet = ss.insertSheet('allMembers', 2);
}
outputSheet.getDataRange().clear();
outputSheet.getRange(1, 1, listArray.length, listArray[0].length).setValues(listArray);
outputSheet.getRange(1, 6, outputSheet.getLastRow(), 4).setHorizontalAlignment("center");
outputSheet.getRange(1, 1, outputSheet.getLastRow(), 1).setHorizontalAlignment("center");
var width = [150, 150, 180, 250, 250, 200];
formatSheet(outputSheet, width);
}
UPDATE
To only list the users in a certain department you would just need to add a if around the push
if(department == '--NAME OF DEPARTMENT--'){
listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, department, title, user.id,]);
}
Using admin SDK and query you can search user on the basis of attributes like OrgName, ManagerId, Ref Linkenter link description here.
Pass query in your request
var queryStr="orgDepartment=HR"
var page = AdminDirectory.Users.list({
domain : 'example.com',
orderBy : 'givenName',
pageToken : pageToken,
query:queryStr
});
My code is not working when I test it in Amazon Developer and I don't see anything wrong with my code. It says my response is invalid.
Here's the code I tried to run but failed(I ran one response but not the other):
var Alexa = require('alexa-sdk');
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
// alexa.dynamoDBTableName = 'YourTableName'; // creates new table for userid:session.attributes
alexa.registerHandlers(handlers);
alexa.execute();
};
var handlers = {
'LaunchRequest': function () {
this.emit('WelcomeIntent');
},
'WelcomeIntent': function () {
this.emit(':ask', 'Welcome to the guessing game! What difficulty would you like to play? Easy, Medium, or Hard?');
},
//------------------------------------------------------------------------------------------------------------------------------------------------
'DifficultyIntent': function (){
var difficulty = this.event.request.intent.slots.difficulty.value;
var range = 10; this.attributes['RandomNumberEnd'] = range;
if (difficulty === 'easy')
{ range = 10;
this.emit[':ask Your range is 1 - ' + range]
}
else if (difficulty === 'medium')
{ range = 100;
this.emit[':ask Your range is 1 - ' + range]
}
else (difficulty === 'hard');
{ range = 1000;
this.emit[':ask Your range is 1 - ' + range]
}
var randomNumber = Math.floor((Math.random()*range)+1);
var rightAnswer = this.attributes['rightAnswer'] = rightAnswer;
}, //check the user's guess with the right answer
'UserGuessIntent': function (){
var guess = this.event.request.intent.slots.guess.value;
this.attributes['guess'] = guess;
this.emit('CheckIntent'); },
'CheckIntent': function (){
var guess = this.attributes['guess'];
this.attributes['rightAnswer'] = randomNumber;
if(guess < rightAnswer){
this.emit(':ask', 'Try Again! Guess higher!');
}
else if(guess > rightAnswer)
{this.emit(':ask', 'Try Again! Guess lower!');
}
else{
this.emit(':tell', 'You are correct! Congratulations!');
}
},
'QuitIntent': function(){
var stop = this.event.request.intent.slots.stop.value;
this.emit('AMAZON.StopIntent');
},
'AMAZON.StopIntent' : function(){
var rightAnswer = this.attributes['rightAnswer'];
this.emit(':tell', 'The right answer is ' + rightAnswer + '. Goodbye!');
}
};