.getValues cannot read Custom Function - javascript

I have to create automated reports with Google Apps Script for an internal client. Straight forward: retrive data, manipulate data, some if tests, and print data in a new format.
My problem is, the source of the data uses a custom function (also designed by me, for date calculation) that is pretty complex, and it is essential for the client, and, apparently, I cannot retrieve the data with the method .getValues from custom functions.
This is the error I get:
9:42:41 AM Error Exception: Cannot convert 'function () { [native code] }' to int.
ARROBA # Scripts Automáticos.gs:5
Is this a real problem in GAS, and is there any workaround this? Or, better, have I coded something wrong? I tried indirect references (like instead of getting the data directly from the custom function, getting it from other cells that referenced that data) but it didn't work.
Here is the line where the problem occurs:
var data = ss.getRange(2, 1, ss.getLastRow, ss.getLastColumn).getValues
Here is on example of codes that do not work:
function ARROBA() {
var ss = SpreadsheetApp.openById([ID]).getSheetByName([sheet])
var data = ss.getRange(2, 1, ss.getLastRow, ss.getLastColumn).getValues
var today = new Date()
var x
var y
for (x = 0; x < data.length; x++) {
if (data[x][34] == "Sim") {
ss.getRange(x+2,7).setValue(data[x][7]+"\n#\n"+(today.getDay+'/'+today.getMonth+'/'+today.getFullYear))
ss.getRange(x+2,34).setValue()
ss.getRange(x+2,35).setValue(data[x][35]+"\n#\n")
ss.getRange(x+2,36).setValue(data[x][36]+"\n#\n")
ss.getRange(x+2,37).setValue(data[x][37]+"\n#\n")
ss.getRange(x+2,38).setValue(data[x][38]+"\n#\n")
}
}
}
And here is the Custom Function:
function SLABANKING (start, startcongelamento, finalcongelamento, startdeclinio, finaldeclinio, cancelamento, end) {
var today = new Date();
var congelamento = 0
var declinio = 0
var x
var y
var z
var s
//typing error handling
if (start == null || start == '') {
return 'Necessário incluir data de início'
} else if(startcongelamento.toString.length != finalcongelamento.toString.length && startcongelamento.toString.length - finalcongelamento.toString.length != 11) {
return 'Erro de preenchimento de datas de congelamento'
} else if(startdeclinio.toString.length != finaldeclinio.toString.length && startdeclinio.toString.length - finaldeclinio.toString.length != 11) {
return 'Erro de preenchimento de datas de reabertura'
} else {
//set de variáveis + complexas
if(startcongelamento.toString().lastIndexOf('#') < 0) {
var sconge = startcongelamento.toString().split('\n')
var fconge = finalcongelamento.toString().split('\n')
var sdec = startdeclinio.toString().split('\n')
var fdec = finaldeclinio.toString().split('\n')
} else {
var sconge = startcongelamento.toString().slice(startcongelamento.toString().lastIndexOf('#')+2, startcongelamento.length).split('\n')
var fconge = finalcongelamento.toString().slice(finalcongelamento.toString().lastIndexOf('#')+2, finalcongelamento.length).split('\n')
var sdec = startdeclinio.toString().slice(startdeclinio.toString().lastIndexOf('#')+2, startdeclinio.length).split('\n')
var fdec = finaldeclinio.toString().slice(finaldeclinio.toString().lastIndexOf('#')+2, finaldeclinio.length).split('\n')
}
//congelamento
if(startcongelamento == null || startcongelamento == undefined || startcongelamento == ''){
} else if(startcongelamento.length != finalcongelamento.length) {
if (startcongelamento.length > 10 && finalcongelamento.length > 10) {
Logger.log('desigual, start e final > 10')
var display = []
for (x = 0; x < sconge.length; x++) {
if (x == sconge.length-1) {
display.push(Math.floor(((Date.parse(today) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)))
} else {
display.push((new Date(fconge[x].toString().slice(3,5)+'/'+fconge[x].toString().slice(0,2)+'/'+fconge[x].toString().slice(6,10)) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)
}
}
for (y = 0; y < display.length; y++) {
congelamento = Number(congelamento) + Number(display[y])
}
return Math.ceil(congelamento)
} else if (startcongelamento.length > 10) {
Logger.log('desigual, só start > 10')
var display = []
for (x = 0; x < sconge.length; x++) {
if (x == sconge.length-1) {
display.push(Math.floor(((Date.parse(today) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)))
} else {
display.push((new Date(fconge) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)
}
}
for (y = 0; y < display.length; y++) {
congelamento = Number(congelamento) + Number(display[y])
}
return Math.ceil(congelamento)
} else {
Logger.log('desigual, nenhum > 10')
congelamento = Math.floor(((Date.parse(today) - new Date(sconge))/8.64E7))
return Math.ceil(congelamento)
}
} else {
if (startcongelamento.length > 10) {
Logger.log('igual, start e final > 10')
for (x = 0; x < sconge.length; x++) {
congelamento = congelamento + (new Date(fconge[x].toString().slice(3,5)+'/'+fconge[x].toString().slice(0,2)+'/'+fconge[x].toString().slice(6,10)) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7
}
} else {
Logger.log('igual, nenhum > 10')
congelamento = (new Date(fconge) - new Date(sconge))/8.64E7
}
}
//declinio
if (startdeclinio == null || startdeclinio == undefined || startdeclinio == ''){
} else {
if (startdeclinio.length > 10) {
Logger.log('declinio, >10')
for (y = 0; y < sdec.length; y++) {
declinio = declinio + (new Date(fdec[y].toString().slice(3,5)+'/'+fdec[y].toString().slice(0,2)+'/'+fdec[y].toString().slice(6,10)) - new Date(sdec[y].toString().slice(3,5)+'/'+sdec[y].toString().slice(0,2)+'/'+sdec[y].toString().slice(6,10)))/8.64E7
}
} else {
Logger.log('declinio, <10')
declinio = (new Date(fdec) - new Date(sdec))/8.64E7
}
}
if (start.length > 10) {
var nstart = start.toString().slice(start.toString().lastIndexOf('#')+2, start.length)
if(cancelamento != null && cancelamento != '') {
return ((((new Date(cancelamento) - new Date(nstart.toString().slice(3,5)+'/'+nstart.toString().slice(0,2)+'/'+nstart.toString().slice(6,10)))/8.64E7 - congelamento) - declinio))
} else if(end != null && end != '') {
return ((((new Date(end) - new Date(nstart.toString().slice(3,5)+'/'+nstart.toString().slice(0,2)+'/'+nstart.toString().slice(6,10)))/8.64E7 - congelamento) - declinio))
} else {
return ((Math.floor((Date.parse(today) - new Date(nstart.toString().slice(3,5)+'/'+nstart.toString().slice(0,2)+'/'+nstart.toString().slice(6,10)))/8.64E7) - congelamento) - declinio)
}
} else {
var nstart = start
if(cancelamento != null && cancelamento != '') {
return ((((new Date(cancelamento) - new Date(start))/8.64E7 - congelamento) - declinio))
} else if(end != null && end != '') {
return ((((new Date(end) - new Date(start))/8.64E7 - congelamento) - declinio))
} else {
return ((Math.floor((Date.parse(today) - new Date(start))/8.64E7) - congelamento) - declinio)
}
}
}
}

So, I got what I was doing wrong. Thanks evolutionxbox, btw, because you sparked my creativity.
I was not actually calling the methods. When the syntax was changed, the code worked.
Don't know if it was a fluke on my part, or if the autocomplete parameters changed, but, regardless, yes, methods must be called and parameters mustn't. :P

Related

Math.pow returning 0 in calc

I'm making a calculator currently and I'm running into an issue with one of the functions, specifically x^y, it keeps returning 0 and not even seeming to run the setInterval at all, though it runs without the if function around it. fn is for which function its using which is x^y, and vi is just a tool in the calculator to distinguish which number you are changing as in reactant, or reactant2, reactants are the 2 numbers that are squared against each other in this case. (this is only the portion of the code with the problem)
function click15(){
if (reactant > 0) {
reactant = parseFloat(reactant);
}
if (reactant2 > 0) {
reactant2 = parseFloat(reactant2);
}
if (fn === 0) {
product = reactant / reactant2;
} else if (fn === 1) {
product = reactant * reactant2;
} else if (fn === 2) {
product = reactant - reactant2;
} else if (fn === 3) {
product = reactant + reactant2;
} else if (fn === 4) {
if (vi === 0) {
vi = 1;
var timer = setInterval(function(){
if (vi === 0) {
product = (Math.pow(reactant, reactant2));
clearInterval(timer);
}
}, 4);
}
}
reactant = product;
product = 0;
reactant2 = "0";
vir = 0;
vir2 = 0;
vi = 0;
di1 = 0;
di2 = 0;
fn = -1;
}

Getting empty data when I'm passing value to an array

I'm just wondering on how I got an empty object, and how to fix it.
tax1 has 16 objects
Payroll controller
if (vm.period === 'Semi-Monthly') {
for (var x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'sm') {
vm.tax2[x] = vm.tax1[x];
}
}
} else if( vm.period === 'Monthly'){
for (var y = 0; y < vm.tax1.length; y++) {
if (vm.tax1[y].eventType === 'm') {
vm.tax2[y] = vm.tax1[y];
}
}
}
Output:
Indices are difficult to read and error-prone, you can consider using .push or .filter
Using .push
vm.tax2 = [];
var eventType;
if (vm.period == 'Semi-Monthly') {
eventType = 'sm';
}
else if( vm.period == 'Monthly') {
eventType = 'm';
}
vm.tax1.forEach(function(item) {
if (item.eventType == eventType) {
vm.tax2.push(item);
}
});
Using .filter
var eventType;
if (vm.period == 'Semi-Monthly') {
eventType = 'sm';
}
else if( vm.period == 'Monthly') {
eventType = 'm';
}
vm.tax2 = vm.tax1.filter(function(item) {
return (item.eventType == eventType);
});
Silly mistake from my side..
here's the fix
var x = 0;
var y = 0;
if (vm.period === 'Semi-Monthly') {
for ( x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'sm') {
vm.tax2[y] = vm.tax1[x];
y++;
}
}
} else if( vm.period === 'Monthly'){
for ( x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'm') {
vm.tax2[y] = vm.tax1[x];
y++;
}
}
}

Change text depending on the time of day and on which button is clicked

I need to display different text 'set' depending on which button I click, and rotate messages in this 'set' depending on what time it is.
This is what I've got:
var date = new Date;
var hh = date.getHours();
var mm = date.getMinutes();
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
var t = hh+":"+mm;
var themessage;
function TimeF() {
if (check == "alt") {
if (t >= "08:00" && t <= "09:00"){
themessage = "A";
}
else if(t >= "09:05" && t <= "10:05"){
themessage = 2;
}
}
else if (check == "NoPack") {
if (t >= "08:00" && t <= "09:14"){
themessage = "NP";
}
else if(t >= "09:19" && t <= "10:33"){
themessage = 2;
}
}
else if (check == "pack") {
if (t >= "08:00" && t <= "09:14") {
themessage = "pack";
}
}
else if (n == 3) {
if (t >= "08:00" && t <= "09:14"){
themessage = "n=3";
}
else if(t >= "09:19" && t <= "10:33"){
themessage = 2;
}
}
else {
if (t >= "08:00" && t <= "09:19") {
themessage = "Else";
}
else if (t >= "09:21" && t<= "10:43"){
themessage =2;
}
}
$('.Test').append(themessage);
}
Also I have button code:
var reg = document.getElementById("Reg");
var pack = document.getElementById("Pack");
var nopack = document.getElementById("NoPack");
var alt = document.getElementById("Alt");
var sch = document.getElementById("Sch");
var check;
var update;
$(document).ready(function () {
$("#Pack").click(function () {
$("#Sch").html("pack");
check = "pack";
});
$("#Reg").click(function () {
$("#Sch").html("Reg");
check = "reg";
});
$("#NoPack").click(function () {
$("#Sch").html("NoPack");
check = "NoPack";
});
$("#Alt").click(function () {
$("#Sch").html("Alternate");
check = "alt";
});
})
The problem is - when I press any button, the code shows the text for 'esle', and not what I supposed to be assigned to that button.
P.S I have jquery refference and I am loading this function TimeF in body.
If you want, I could make a quick CodePen with this.
P.S.S n==3 in my code - is checking if it is Wednesday.

Stacks with Javascript

I am working with stacks on the infamous 'Braces' problem and I got to a halt. This should be an easy fix but my eyes are not much of a help at the moment.
The first call to the function is working like a charm but the second one is running an extra time and I can't see why.
The first call returns 01110 which is correct but the second returns 011110 which is not...
If you can't read the code here, got to the fiddle
//constructor function for our Stack class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function peek() {
return this.dataStore[this.top - 1];
}
function length() {
return this.top;
}
function clear() {
this.top = 0;
}
function braces(expression) {
for (var i = 0; i < expression.length; i++) {
//if the number of elements in the expression is odd, it is guaranteed not to have a matching expression
//therefore we print 0
if (expression[i].length%2 !== 0) {
console.log(0);
} else {
var s = new Stack();
var startPoint = expression[i].charAt(0);
//if the expression starts with an open brace it means we will not have a matching expression so we print 0
if (startPoint == '(' || startPoint == '{' || startPoint == '[') {
for (var j = 0; j < expression[i].length; j++) {
var char = expression[i].charAt(j);
var h = '';
if (char == '(' || char == '{' || char == '[') {
s.push(char);
} else {
h = s.peek();
if (h == "(" && char == ")") {
s.pop();
} else if (h == "{" && char == "}") {
s.pop();
} else if (h == "[" && char == "]") {
s.pop();
}
}
}
} else {
console.log(0);
}
if (s.length() == 0) {
console.log(1)
} else {
console.log(0);
}
}
}
}
var expr = [ "}()()", "[]({})", "([])", "{()[]}", "([)]" ]; //working
var expr2 = [ "}()(){", "[]({})", "([])", "{()[]}", "([)]" ]; //running an extra time
braces(expr);
Change this:
else {
console.log(0);
continue; //this is new
}
if (s.length() == 0) {
Your function would log both 0 and 1/0 if the startpoint is not { or ( or [ and the length of s was 0
Your stack functions are all outside of the scope of Stack() and therefore the data probably won't be what you expect. You can start fixing this by putting functions inside the Stack() function:
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
this.pop = function () {
// pop
}
this.push = function () {
// code
}
this.peek = function () {
// code
}
}
That way, the methods all have access to the same data.

onClick of javascript not working in Browser like chrome,firefox

Sir,
I have Javascript calendar(for Picking a date) downloaded from Internet. i am able to pick a appropriate Date when working in IE 6 version. But it is unable to pick a date(on click not working) when I am using Modern Browser like Google chrome. here is code Snippet. Advice Kindly!
calendar.js file
monthMaxDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
monthMaxDaysLeap= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
hideSelectTags = [];
function getRealYear(dateObj)
{
return (dateObj.getYear() % 100) +
(((dateObj.getYear() % 100) < 39) ? 2000 : 1900);
}
function getDaysPerMonth(month, year)
{
/*
Check for leap year. These are some conditions to check
year is leap year or not...
1.Years evenly divisible by four are normally leap years, except for...
2.Years also evenly divisible by 100 are not leap years, except for...
3.Years also evenly divisible by 400 are leap years.
*/
if ((year % 4) == 0)
{
if ((year % 100) == 0 && (year % 400) != 0)
return monthMaxDays[month];
return monthMaxDaysLeap[month];
}
else
return monthMaxDays[month];
}
function createCalender(year, month, day)
{
// current Date
var curDate = new Date();
var curDay = curDate.getDate();
var curMonth = curDate.getMonth();
var curYear = getRealYear(curDate)
// if a date already exists, we calculate some values here
if (!year)
{
var year = curYear;
var month = curMonth;
}
var yearFound = 0;
for (var i=0; i<document.getElementById('selectYear').options.length; i++)
{
if (document.getElementById('selectYear').options[i].value == year)
{
document.getElementById('selectYear').selectedIndex = i;
yearFound = true;
break;
}
}
if (!yearFound)
{
document.getElementById('selectYear').selectedIndex = 0;
year = document.getElementById('selectYear').options[0].value;
}
document.getElementById('selectMonth').selectedIndex = month;
// first day of the month.
var fristDayOfMonthObj = new Date(year, month, 1);
var firstDayOfMonth = fristDayOfMonthObj.getDay();
continu = true;
firstRow = true;
var x = 0;
var d = 0;
var trs = []
var ti = 0;
while (d <= getDaysPerMonth(month, year))
{
if (firstRow)
{
trs[ti] = document.createElement("TR");
if (firstDayOfMonth > 0)
{
while (x < firstDayOfMonth)
{
trs[ti].appendChild
(document.createElement ("TD"));
x++;
}
}
firstRow = false;
var d = 1;
}
if (x % 7 == 0)
{
ti++;
trs[ti] = document.createElement("TR");
}
if ( day && d == day)
{
var setID = 'calenderChoosenDay';
var styleClass = 'choosenDay';
var setTitle = 'this day is currently selected';
}
else if (d == curDay && month == curMonth && year == curYear)
{
var setID = 'calenderToDay';
var styleClass = 'toDay';
var setTitle = 'this day today';
}
else
{
var setID = false;
var styleClass = 'normalDay';
var setTitle = false;
}
var td = document.createElement("TD");
td.className = styleClass;
if (setID)
{
td.id = setID;
}
if (setTitle)
{
td.title = setTitle;
}
td.onmouseover = new Function('highLiteDay(this)');
td.onmouseout = new Function('deHighLiteDay(this)');
*if (targetEl)
td.onclick = new Functio*
('pickDate ('+year+', '+month+', '+d+')');
else
td.style.cursor = 'default';
td.appendChild(document.createTextNode(d));
trs[ti].appendChild(td);
x++;
d++;
}
return trs;
}
function showCalender(elPos, tgtEl)
{
targetEl = false;
if (document.getElementById(tgtEl))
{
targetEl = document.getElementById(tgtEl);
}
else
{
if (document.forms[0].elements[tgtEl])
{
targetEl = document.forms[0].elements[tgtEl];
}
}
var calTable = document.getElementById('calenderTable');
var positions = [0,0];
var positions = getParentOffset(elPos, positions);
calTable.style.left = positions[0]+'px';
calTable.style.top = positions[1]+'px';
calTable.style.display='block';
var matchDate = new RegExp('^([0-9]{2})-([0-9]{2})-([0-9]{4})$');
var m = matchDate.exec(targetEl.value);
if (m == null)
{
trs = createCalender(false, false, false);
showCalenderBody(trs);
}
else
{
if (m[1].substr(0, 1) == 0)
m[1] = m[1].substr(1, 1);
if (m[2].substr(0, 1) == 0)
m[2] = m[2].substr(1, 1);
m[2] = m[2] - 1;
trs = createCalender(m[3], m[2], m[1]);
showCalenderBody(trs);
}
hideSelect(document.body, 1);
}
function showCalenderBody(trs)
{
var calTBody = document.getElementById('calender');
while (calTBody.childNodes[0])
{
calTBody.removeChild(calTBody.childNodes[0]);
}
for (var i in trs)
{
calTBody.appendChild(trs[i]);
}
}
function setYears(sy, ey)
{
// current Date
var curDate = new Date();
var curYear = getRealYear(curDate);
if (sy)
startYear = curYear;
if (ey)
endYear = curYear;
document.getElementById('selectYear').options.length = 0;
var j = 0;
for (y=ey; y>=sy; y--)
{
document.getElementById('selectYear')[j++] = new Option(y, y);
}
}
function hideSelect(el, superTotal)
{
if (superTotal >= 100)
{
return;
}
var totalChilds = el.childNodes.length;
for (var c=0; c<totalChilds; c++)
{
var thisTag = el.childNodes[c];
if (thisTag.tagName == 'SELECT')
{
if (thisTag.id != 'selectMonth' && thisTag.id != 'selectYear')
{
var calenderEl = document.getElementById ('calenderTable');
var positions = [0,0];
var positions = getParentOffset(thisTag, positions); // nieuw
var thisLeft = positions[0];
var thisRight = positions[0] + thisTag.offsetWidth;
var thisTop = positions[1];
var thisBottom = positions[1] + thisTag.offsetHeight;
var calLeft = calenderEl.offsetLeft;
var calRight = calenderEl.offsetLeft + calenderEl.offsetWidth;
var calTop = calenderEl.offsetTop;
var calBottom = calenderEl.offsetTop + calenderEl.offsetHeight;
if (
(
/* check if it overlaps horizontally */
(thisLeft >= calLeft && thisLeft <= calRight)
||
(thisRight <= calRight && thisRight >= calLeft)
||
(thisLeft <= calLeft && thisRight >= calRight)
)
&&
(
/* check if it overlaps vertically */
(thisTop >= calTop && thisTop <= calBottom)
||
(thisBottom <= calBottom && thisBottom >= calTop)
||
(thisTop <= calTop && thisBottom >= calBottom)
)
)
{
hideSelectTags[hideSelectTags.length] = thisTag;
thisTag.style.display = 'none';
}
}
}
else if(thisTag.childNodes.length > 0)
{
hideSelect(thisTag, (superTotal+1));
}
}
}
function closeCalender()
{
for (var i=0; i<hideSelectTags.length; i++)
{
hideSelectTags[i].style.display = 'block';
}
hideSelectTags.length = 0;
document.getElementById('calenderTable').style.display='none';
}
function highLiteDay(el)
{
el.className = 'hlDay';
}
function deHighLiteDay(el)
{
if (el.id == 'calenderToDay')
el.className = 'toDay';
else if (el.id == 'calenderChoosenDay')
el.className = 'choosenDay';
else
el.className = 'normalDay';
}
function pickDate(year, month, day)
{
month++;
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
if (!targetEl)
{
alert('target for date is not set yet');
}
else
{
targetEl.value= year+'-'+month+'-'+day;
closeCalender();
}
}
function getParentOffset(el, positions)
{
positions[0] += el.offsetLeft;
positions[1] += el.offsetTop;
if (el.offsetParent)
positions = getParentOffset(el.offsetParent, positions);
return positions;
}
Wow, new Function()? Really?
td.onmouseover = function() {highLiteDay(this);};
td.onmouseout = function() {deHighLiteDay(this);};
// the above two should probably just be `:hover` styles in CSS
(function(year,month,d) {
td.onclick = function() {pickDate(year, month, d);};
})(year,month,d);
// this creates a closure to "anchor" the values of the variables
// even as the loop iterates

Categories

Resources