I have this JS code which pulls data out of xml table
GDownloadUrl("phpsqlajax_genxm1l.php", function(data) {
var xml = GXml.parse(data);
var markerid = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markerid.length; i++) {
var type = markerid[i].getAttribute("type");
//var point = new GLatLng(parseFloat(markerid[i].getAttribute("lat")),
//parseFloat(markerid[i].getAttribute("lng")));
var date = markerid[i].getAttribute("date");
//tabelis punkt "point" stringiks, keskelt pooleks ja 2 uut väärtust markeri atribuutideks
var punktx = markerid[i].getAttribute("point");
var kommentaar = markerid[i].getAttribute("kommentaar");
var punkt = punktx.toString();
var temp = new Array();
temp = punkt.split(",");
var point = new GLatLng(temp[0],temp[1])
var marker = createMarker(point, date, type, kommentaar);
map.addOverlay(marker);
}
});
How can I do so, that when I press a button, the script only takes data entered between certain time/date?
Depending on the date/time format in the XML, this is very simple:
for (var i = 0; i < markerid.length; i++) {
var date = markerid[i].getAttribute("date");
if (date >= fromDate && date < toDate) {
// etc etc
}
}
This would require the date attribute (and both fromDate/toDate, of course) to be a string in a string-comparable date-format (like "yyyy-dd-mm hh:nn:ss").
If this is not the case, you probably must convert them to Date objects first, the comparison stays the same.
Related
I'm grabbing a spreadsheet from an online report the file is a CSV file I format so is usable by gscript.
So I'm counting everything that's a value over 0 in a loop and using an array. but when displaying the information in one value less...so let's say there are 7 values on the sheet the logger displays 6...I'm super new on this so I'll appreciate any help.
The commission variable is the one with the issue
function start()
{
var startDate = new Date();
var endDate = new Date();
var sMonth = startDate.getMonth()+1; //start day variables
var sDay = startDate.getDate()-3;
var sYear = startDate.getFullYear();
startDate = sMonth+"-"+sDay+"-"+sYear; //concatenate date
endDate = startDate;
var csvUrl = "http://publisherpro.flexoffers.com/Report/Public?gui=9ce2029a-e14c-4548-a1af-0f0e2e8894c8&d1=" +startDate+"&d2="+endDate+ "&t=A&o=CSV"
Logger.log(csvUrl);
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText(); //
Just formating the file to be useable within Google Scripts
var csvData = Utilities.parseCsv(csvContent); // Same as above //Returns a tabular 2D array representation of a CSV string.
var counter = new Array;
var commision = 0;
for (var c = 2; c < csvData.length; c++) {
if (csvData[c][21] > 0)
{
commision++
}
}
Logger.log(commision)
}
I'm trying to run an IF function to match the date in the first column to "last month" and the date in the last column to "newest date" and copy and paste all of the rows matching this criteria (excluding the first and last column) to the bottom of the list.
This is the script I'm running and it isn't finding any matches when I know for a fact there are at least 100 rows matching this criteria:
function myFunction() {
var MCS = SpreadsheetApp.openById('[ID REMOVED FOR THIS Q]');
var MRB = MCS.getSheetByName('Media Rates Back');
var MRBrange = MRB.getRange(1,1,MRB.getLastRow(),1).getValues();
var dest = MRBrange.filter(String).length + 1;
var LM = new Date();
LM.setDate(1);
LM.setMonth(LM.getMonth()-1);
var LMs = Date.parse(LM);
var Datenew = MRB.getRange(MRB.getLastRow(),MRB.getLastColumn()).getValue();
var Datecol = MRB.getRange(1,6,MRB.getLastRow(),1).getValues();
var Datenews = Date.parse(Datenew);
for(var i=0; i<MRBrange.length; i++) {
if(Date.parse(MRBrange[i])==LMs && Date.parse(Datecol[i])==Datenews ) {
var NewRange = MRB.getRange(i,2,(MRB.getLastRow()-i),5);
var NewRangeV = NewRange.getValues();
var destination = MRB.getRange(MRB.getLastRow()+1,2);
Logger.log(NewRange);
NewRange.copyTo(destination);
}else{
Logger.log(i);
}
}}
Any help would be appreciated!
Rather than get the columns as separate ranges, I would get the entire range as one array, then loop over that and check the two columns.
I'm also assuming your values are formatted as dates in the Sheet, in which case you don't need to use Date.parse(), and that your actual date logic is correct.
You can try using the debugger and set a breakpoint at the IF, so you can check the values it is comparing. or put a Logger.log call to list your comparisons.
var last_month_column = 1;
var newest_date_column = MRB.getLastColumn();
var MRBrange = MRB.getRange(1,1,MRB.getLastRow(),newest_date_column).getValues();
for(var row in MRBrange) {
if(MRBrange[row][last_month_column]==LMs && Datecol[row][newest_date_column] ==Datenews ) {
/* your copy logic here */
}else{
Logger.log(i);
}
}
I think the problem may be that MRBrange is a 2d Array. So I used another loop to convert it to a 1d array.
function myFunction() {
var MCS = SpreadsheetApp.openById('[ID REMOVED FOR THIS Q]');
var MRB = MCS.getSheetByName('Media Rates Back');
var MRBrangeA = MRB.getRange(1,1,MRB.getLastRow(),1).getValues();//2d array
var MRBrange=[];
for(var i=0;i<MRBrangeA.length;i++)
{
MRBrange.push(MRBrangA[i][0]);//1d array
}
var dest = MRBrange.filter(String).length + 1;
var LM = new Date();//current day
LM.setDate(1);//first day of month
LM.setMonth(LM.getMonth()-1);//first day of last month
var LMs = Date.parse(LM);
var Datenew = MRB.getRange(MRB.getLastRow(),MRB.getLastColumn()).getValue();
var Datecol = MRB.getRange(1,6,MRB.getLastRow(),1).getValues();
var Datenews = Date.parse(Datenew);
for(var i=0; i<MRBrange.length; i++) {
if(Date.parse(MRBrange[i])==LMs && Date.parse(Datecol[i])==Datenews ) {
var NewRange = MRB.getRange(i,2,(MRB.getLastRow()-i),5);
var NewRangeV = NewRange.getValues();
var destination = MRB.getRange(MRB.getLastRow()+1,2);
Logger.log(NewRange);
NewRange.copyTo(destination);
}else{
Logger.log(i);
}
}}
I have a Google AdWords script that is taking yesterdays cumulative spend (filtered) and inputting the value into a Google Sheet row. The logic I have in place is tested and works correctly, but when I try to replicate the logic for a different filter condition the value that is passed back for the replicated logic comes back with a value of 0. I believe the issues has to do with my .withCondition filter logic, but it looks correct to me.
Adwords Script:
function main() {
var sheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1kKPwvazsT9YOfL5swKRkjHYAdUtetetetetetet/edit#gid=0").getActiveSheet();
var emptyRow = findEmptyRow(sheet);
var yesterday = new Date(new Date()-1);
var range = sheet.getRange(emptyRow + 1, 1, 1, 10);
var row = range.getValues();
var campaignIteratorPaidSearch = AdWordsApp.campaigns().withCondition("Name NOT_IN ['Remarketing', 'GSP', 'YouTube'] ").forDateRange('YESTERDAY').get();
var campaignIteratorDisplay = AdWordsApp.campaigns().withCondition("Name IN ['Remarketing', 'GSP', 'YouTube'] ").forDateRange('YESTERDAY').get();
var totalPaidSearchCost = 0;
var totalDisplayCost = 0;
var date = new Date();
date.setDate(date.getDate() - 1);
//Paid Search Spend
while (campaignIteratorPaidSearch.hasNext()) {
var campaignStats = campaignIteratorPaidSearch.next();
var stats = campaignStats.getStatsFor('YESTERDAY');
totalPaidSearchCost += stats.getCost();
}
//Display Spend
while (campaignIteratorDisplay.hasNext()) {
var displayCampaignStats = campaignIteratorDisplay.next();
var displayStats = displayCampaignStats.getStatsFor('YESTERDAY');
totalDisplayCost += displayStats.getCost();
}
row[0][0] = date;
row[0][1] = totalPaidSearchCost;
row[0][2] = totalDisplayCost;
range.setValues(row);
}
function findEmptyRow(sheet) {
var dates = sheet.getRange(1, 1, 365, 1).getValues();
for (var emptyDate = 0; emptyDate < dates.length; emptyDate++) {
if (dates[emptyDate][0].length == 0) {
return emptyDate;
}
}
}
The campaign name is a String so you can not use NOT_IN and IN operators, you should use:
= != STARTS_WITH STARTS_WITH_IGNORE_CASE CONTAINS CONTAINS_IGNORE_CASE DOES_NOT_CONTAIN DOES_NOT_CONTAIN_IGNORE_CASE
https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_campaignselector#withCondition_1
I'm working on a calendar that will allow users to store events on a given date. when I update the calendar each new month I create new nodes and assign them an id so I will be able to append something to them later like so:
var i = 1;
for(var w in weeks){
var days = weeks[w].getDates();
// days contains normal JavaScript Date objects.
// alert("Week starting on "+days[0]);
var which_week = "week"+i;
i++;
for(var d in days){
console.log(days[d].toISOString());
var tr = document.getElementById(which_week);
if(days[d].getMonth()==month){
var newDay = document.createElement("div");
newDay.appendChild(document.createTextNode(days[d].getDate()));
//alert(newDay.data);
newDay.setAttribute("id", newDay.lastChild.data);
$(tr).append('<td><a class="linky" href="#">'+newDay.lastChild.data+'</a></td>');
}
else{
$(tr).append('<td class="disabledCell"><a class="linky disabledLink" href="#">'+days[d].getDate()+'</a></td>');
}
}
}
getEvents();
}
I modify the nodes:
function ajaxEventCallback(event){
var data = event.target.responseText;
data = JSON.parse(event.target.responseText);
for (var i = 0; i < data.length; i++)
//alert("event: " + data[i].title);
//
var dayOfEvent= data[i].day;
document.getElementById(dayOfEvent).appendChild(data[i].title);
}
I get a "cannot read property append child of null" error on the last line of code. I think it's a scoping issue but I don't know where to begin solving it.
At the global scope:
var allWeeks = [];
In the first function:
var i = 1;
for(var w in weeks){
var days = weeks[w].getDates();
// days contains normal JavaScript Date objects.
// week object used to store the days until it is added to the array
var week = [];
var which_week = "week"+i;
i++;
for(var d in days){
console.log(days[d].toISOString());
var tr = document.getElementById(which_week);
if(days[d].getMonth()==month){
// add the day to the temporary week object
week.push(days[d].getDate());
$(tr).append('<td><a class="linky" href="#">' + days[d].getDate() + '</a></td>');
}
else{
$(tr).append('<td class="disabledCell"><a class="linky disabledLink" href="#">'+days[d].getDate()+'</a></td>');
}
}
// add the temporary week array to the array of weeks
allWeeks.push(week);
}
In the ajax event:
function ajaxEventCallback(event){
var data = event.target.responseText;
data = JSON.parse(event.target.responseText);
for (var i = 0; i < data.length; i++) {
var dayOfEvent = data[i].day;
// Here you add the event to the appropriate day in the array
}
}
Looking to extend my javascript object, I want to find the minium and maximum of a multicolumn csvfile. I have looked up solutions but I cannot really grasp the right way. I found a solution here: Min and max in multidimensional array but I do not get an output.
My code that I have for now is here:
function import(filename)
{
var f = new File(filename);
var csv = [];
var x = 0;
if (f.open) {
var str = f.readline(); //Skips first line.
while (f.position < f.eof) {
var str = f.readline();
csv.push(str);
}
f.close();
} else {
error("couldn't find the file ("+ filename +")\n");
}
for (var i=(csv.length-1); i>=0; i--) {
var str = csv.join("\n");
var a = csv[i].split(","); // convert strings to array (elements are delimited by a coma)
var date = Date.parse(a[0]);
var newdate = parseFloat(date);
var open = parseFloat(a[1]);
var high = parseFloat(a[2]);
var low = parseFloat(a[3]);
var close = parseFloat(a[4]);
var volume = parseFloat(a[5]);
var volume1000 = volume /= 1000;
var adjusted_close = parseFloat(a[6]);
outlet(0, x++, newdate,open,high,low,close,volume1000,adjusted_close); // store in the coll
}
}
Edit
What if, instead of an array of arrays, you use an array of objects? This assumes you're using underscore.
var outlet=[];
var outletkeys=['newdate','open','high','low','close','volume','volume1000','adjusted_close'];
for (var i=(csv.length-1);i>0; i--) {
var a = csv[i].split(",");
var date = Date.parse(a[0]);
var volume = parseFloat(a[5],10);
outlet.push( _.object(outletkeys, [parseFloat(date,10) , parseFloat(a[1],10) , parseFloat(a[2],10) , parseFloat(a[3],10) , parseFloat(a[4],10) , parseFloat(a[5],10) , volume /= 1000 , parseFloat(a[6],10) ]) );
}
Then the array of the column 'open' would be
_.pluck(outlet,'open');
And the minimum it
_.min(_.pluck(outlet,'open'));
Edit2
Let's forget about underscore for now. I believe you need to get the maximum value on the second column, which is what you put in your open variable.
¿Would it help if you could have that value right after the for loop? For example
var maxopen=0;
for (var i=(csv.length-1); i>=0; i--) {
var a = csv[i].split(",");
var date = Date.parse(a[0]);
var newdate = parseFloat(date);
var open = parseFloat(a[1]);
maxopen=(open>maxopen)? open : maxopen; // open overwrites the max if it greater
...
...
outlet(0, x++, newdate,open,high,low,close,volume1000,adjusted_close);
}
console.log('Maximum of open is',maxopen);