Adding up text box numbers with AS3 - actionscript-3

I've been have a heck of a time doing all this. I hope everyone can help.So... what this is doing is taking 9 text box number and adding them up in a dynamic text box. So here are my problems.
How can I replace an empty text box with a 0, if the user gets rid of the 0 that is already in there its will come out NaN. The if statements below were supposed to fix it, maybe someone can improve it.
stage.addEventListener(Event.CHANGE, checkTotal);
nextQuestion_btn.addEventListener(MouseEvent.MOUSE_DOWN, nextQuestion);
function checkTotal(e:Event){
var work:Number = parseInt(work_txt.text);
var rnr:Number = parseInt(rnr_txt.text);
var exerciseB:Number = parseInt(exerciseB_txt.text);
var exerciseM:Number = parseInt(exerciseM_txt.text);
var chores:Number = parseInt(chores_txt.text);
var social:Number = parseInt(social_txt.text);
var food:Number = parseInt(food_txt.text);
var twt:Number = parseInt(twt_txt.text);
var partying:Number = parseInt(partying_txt.text);
var other:Number = parseInt(other_txt.text);
if(work_txt.text==""){
work=0;
}
if(rnr_txt.text==""){
rnr=0;
}
if(exerciseB_txt.text==""){
exerciseB=0;
}
if(exerciseM_txt.text==""){
exerciseM=0;
}
if(chores_txt.text==""){
chores=0;
}
if(social_txt.text==""){
social=0;
}
if(food_txt.text==""){
food=0;
}
if(twt_txt.text==""){
twt=0;
}
if(partying_txt.text==""){
partying=0;
}
if(other_txt.text==""){
other=0;
}
var total400:Number = work + rnr + exerciseB + exerciseM +
chores + social + food + twt + partying + other;
I can't let my text boxes add up over 400 so as the user types in 399 into one box, if the user types 2 into the next that current text box will revert to 0 because it would be over 400.
I was told using e.currentTarget could solve that problem but I'm not sure how to use it.
All my code...This is my first time on this site so please forgive me for my noobness.
work_txt.maxChars = 3;
rnr_txt.maxChars = 3;
exerciseB_txt.maxChars = 3;
exerciseM_txt.maxChars = 3;
chores_txt.maxChars = 3;
social_txt.maxChars = 3;
food_txt.maxChars = 3;
twt_txt.maxChars = 3;
partying_txt.maxChars = 3;
other_txt.maxChars = 3;
work_txt.restrict = "0-9"
rnr_txt.restrict = "0-9"
exerciseB_txt.restrict = "0-9"
exerciseM_txt.restrict = "0-9"
chores_txt.restrict = "0-9"
social_txt.restrict = "0-9"
food_txt.restrict = "0-9"
twt_txt.restrict = "0-9"
partying_txt.restrict = "0-9"
other_txt.restrict = "0-9";
/*work_txt.text = "0";
rnr_txt.text = "0";
exerciseB_txt.text = "0";
exerciseM_txt.text = "0";
chores_txt.text = "0";
social_txt.text = "0";
food_txt.text = "0";
twt_txt.text = "0";
partying_txt.text = "0";
other_txt.text = "0";*/
var survival:Number = 0;
nextQuestion_btn.visible=false;
stage.addEventListener(Event.CHANGE, checkTotal);
nextQuestion_btn.addEventListener(MouseEvent.MOUSE_DOWN, nextQuestion);
function checkTotal(e:Event){
var work:Number = parseInt(work_txt.text);
var rnr:Number = parseInt(rnr_txt.text);
var exerciseB:Number = parseInt(exerciseB_txt.text);
var exerciseM:Number = parseInt(exerciseM_txt.text);
var chores:Number = parseInt(chores_txt.text);
var social:Number = parseInt(social_txt.text);
var food:Number = parseInt(food_txt.text);
var twt:Number = parseInt(twt_txt.text);
var partying:Number = parseInt(partying_txt.text);
var other:Number = parseInt(other_txt.text);
if(work_txt.text==""){
work=0;
}
if(rnr_txt.text==""){
rnr=0;
}
if(exerciseB_txt.text==""){
exerciseB=0;
}
if(exerciseM_txt.text==""){
exerciseM=0;
}
if(chores_txt.text==""){
chores=0;
}
if(social_txt.text==""){
social=0;
}
if(food_txt.text==""){
food=0;
}
if(twt_txt.text==""){
twt=0;
}
if(partying_txt.text==""){
partying=0;
}
if(other_txt.text==""){
other=0;
}
var total400:Number = work + rnr + exerciseB + exerciseM +
chores + social + food + twt + partying + other;
trace(work);
trace(rnr);
trace(exerciseB);
trace(exerciseM);
trace(chores);
trace(social);
trace(food);
trace(twt);
trace(partying);
trace(other);
trace(total400);
total400_txt.text = String(total400);
if(total400 >= 400){
nextQuestion_btn.visible=true;
}else{
nextQuestion_btn.visible=false;
}
}

Q1
If the values only can be int type, try to use int instead of Number
var work:int = parseInt(work_txt.text);//work will be 0 if the text is empty
Q2
If you want revert the text to 0(the text box which input 2)
function checkTotal(e:Event){
var target:TextField = e.target as TextField;
if(total400 >= 400){
if (target) {//you may check if target is one of the text box you have listed.
target.text = "0";
}
nextQuestion_btn.visible=true;
}
}

Related

Monty Hall Problem, resetGame is behaving weirdly

Basically the code (you guys probably can write it much cleaner than I) works perfectly on the first run through.
var doorSelection = ["a", "b", "c"];
var started = false;
var notPicked = true;
var notFinalChosen = true;
var wins = 0;
var losses = 0;
let roundComplete = false;
document.querySelector(".scoreCorrect").textContent = wins;
document.querySelector(".scoreWrong").textContent = losses;
document.querySelector(".heresText").classList.add("invisible");
document.querySelector(".startButton").addEventListener("click", function(){
document.querySelector(".startButton").classList.add("invisible");
mhGame();
started = true;
})
function mhGame(){
document.querySelector(".heresText").classList.remove("invisible");
var doorNumber = Math.floor(Math.random() * 3);
var doorPicker = doorSelection[doorNumber];
console.log(doorNumber + " " + doorPicker);
var doorContainer = document.querySelectorAll(".doorcontainer")[doorNumber];
var car = document.querySelector(".car");
car.classList.remove("invisible");
var doorContainerRect = doorContainer.getBoundingClientRect();
var carRect = car.getBoundingClientRect();
var carPosLeft = doorContainerRect.left - carRect.left + 50;
var carPosTop = doorContainerRect.top - carRect.top + 240;
car.style.left = carPosLeft + "px";
car.style.top = carPosTop + "px";
for(var i=0; i<3; i++){
document.querySelectorAll(".doorcontainer")[i].addEventListener("click", function(){
if (started && notPicked){
var firstPicked = this.textContent.trim();
console.log(firstPicked);
darkenDoor(firstPicked);
notPicked = false;
setTimeout(function(){
var doorsLeft = doorSelection.filter(function(door) {
return door !== firstPicked && door !== doorPicker;
});
var doorToReveal = doorsLeft[Math.floor(Math.random() * doorsLeft.length)];
console.log(doorToReveal);
hostReveal(doorToReveal);
document.querySelector(".heresText").classList.add("invisible");
document.querySelector(".switch").classList.remove("invisible");
document.querySelector(".stay").classList.remove("invisible");
for(var j=0; j<2; j++){
document.querySelectorAll(".buttonChoice div")[j].addEventListener("click", function(){
if(notFinalChosen){
var finalChoice = this.textContent;
if (finalChoice === "Switch"){
removeDarken(firstPicked);
var finalDoor = doorSelection.filter(function(newdoor){
return newdoor !== firstPicked && newdoor !== doorToReveal;
})
var openFinalChoice = "." + finalDoor + " .door";
document.querySelector(openFinalChoice).classList.add("invisible");
notFinalChosen = false;
console.log(finalDoor + ", " + doorPicker);
if(finalDoor == doorPicker){
document.querySelector(".heading").textContent = "You Win!";
wins++;
}
else{
document.querySelector(".heading").textContent = "Fail!";
losses++;
}
document.querySelector(".scoreCorrect").textContent = wins;
document.querySelector(".scoreWrong").textContent = losses;
}
else {
var openFinalChoice = "." + firstPicked + " .door";
removeDarken(firstPicked);
document.querySelector(openFinalChoice).classList.add("invisible");
notFinalChosen = false;
if(firstPicked === doorPicker){
document.querySelector(".heading").textContent = "You Win!";
wins++;
}
else{
document.querySelector(".heading").textContent = "Fail!";
losses++;
}
document.querySelector(".scoreCorrect").textContent = wins;
document.querySelector(".scoreWrong").textContent = losses;
}
}
resetGame();
})
}
}, 2000)
}
})
}
}
function darkenDoor(varsTemp){
var doorVars = document.querySelector("." + varsTemp);
doorVars.classList.add("darken");
}
function removeDarken(varsTemp2){
var doorVars2 = document.querySelector("." + varsTemp2);
doorVars2.classList.remove("darken");
}
function hostReveal(revealed){
var revealedDoor ="." + revealed + " .door";
document.querySelector(revealedDoor).classList.add("invisible");
}
function resetGame(){
setTimeout(function(){
console.log(doorSelection);
roundComplete = false;
started = false;
notPicked = true;
notFinalChosen = true;
document.querySelector(".switch").classList.add("invisible");
document.querySelector(".stay").classList.add("invisible");
document.querySelector(".car").classList.add("invisible");
document.querySelector(".car").style.left = 0 + "px";
document.querySelector(".car").style.top = 0 + "px";
document.querySelector(".startButton").classList.remove("invisible");
doorPicker = null;
doorNumber = null;
doorToReveal = null;
finalChoice = null;
finalDoor = null;
doorsLeft = null;
openFinalChoice = null;
for(var m=0; m<doorSelection.length; m++){
document.querySelectorAll(".door")[m].classList.remove("invisible");
}
document.querySelector(".heading").textContent = "Welcome to the Monty Hall Game!";
}, 3000)
}
But once I call resetGame(); and I've tried many different things including a true/false statement to trigger it, and placing it in different places (I have no idea what I'm doing with this part now), it opens the door with the car in it on the second round, then doesn't remove the "darken" by the third round, and by maybe the 4th or 5th round, the "start" button stops working as a whole.

I need to merge text of 2 lines depending on their x1,x2,y1 and y2 values

I am working on HOCR format of tesseract OCR, i am stuck when i have a text based on multiple lines. HOCR Format contains bounding box for every word and multi-line text issue can be solve if i merge all the texts of words if they have same x1.
I am using java script for this task.
This is sample image i am using, due to privacy issues i have masked the confidential data.
Here is my code, i know its not well written so i am open to any cretic.
//merging 2 lines(currentLine, previousLine)
function merge2lines(ocrLine, ocrPrevLine)
{
var stringOutCome="";
var stringOutComeOuterLine="";
//get all the words in this line
var lineItems = $(ocrLine).children();
var CoordinatesOfItemForFirstLineOfSecondLine='';
var textOfItemForFirstLineOfSecondLine='';
var prevLineItems = $(ocrPrevLine).children();
//loop over all words
var lineItemsCount = lineItems.length;
for (var i=0;i<lineItemsCount;i++)
{
var stringInfo = lineItems[i].textContent;
if (typeof stringInfo === 'string' && stringInfo.trim().length > 0)
{
var str = lineItems[i].title;
var title = (str).split(";");
var firstSpace = title[0].indexOf(" ");
var newStr = title[0].slice(firstSpace);
var coordinates = newStr.split(' ');
if(i==0){
CoordinatesOfItemForFirstWordOfSecondLine = coordinates;
textOfItemForFirstWordOfSecondLine = lineItems[i].textContent;
}
//check and remove text
if(! stringOutComeOuterLine.includes(lineItems[i].textContent))
{
stringOutComeOuterLine = stringOutComeOuterLine+" "+lineItems[i].textContent;
}
// stringOutComeOuterLine = stringOutComeOuterLine+" "+lineItems[i].textContent;
if(i<lineItemsCount-1)
{
var str2 = lineItems[i+1].title;
var title2 = (str2).split(";");
var firstSpace2 = title2[0].indexOf(" ");
var newStr2 = title2[0].slice(firstSpace2);
var coordinates2 = newStr2.split(' ');
var differenceOfCordinates = Math.abs(coordinates[3] - coordinates2[1]);
// console.log(lineItems[i].textContent,+" pakistan <- -> Block B",lineItems[i+1].textContent," DIfference: ",differenceOfCordinates);
if(parseInt(differenceOfCordinates) < 100)
{
stringOutComeOuterLine = stringOutComeOuterLine+" "+lineItems[i+1].textContent;
}
else{
var check = true;
// check previousLineitem x
for (var j=0;j<prevLineItems.length;j++)
{
var prevString = prevLineItems[j].textContent;
if (typeof prevString === 'string' && prevString.trim().length > 0)
{
var previousLineTitle = prevLineItems[j].title;
var splittedPreviousLineTitle = (previousLineTitle).split(";");
var previousLineItemFirstSpace = splittedPreviousLineTitle[0].indexOf(" ");
var previousLineItemCoordinates = splittedPreviousLineTitle[0].slice(previousLineItemFirstSpace);
var previousLineItemCoordinatesList = previousLineItemCoordinates.split(' ');
var stringDifference = Math.abs(previousLineItemCoordinatesList[1] - CoordinatesOfItemForFirstWordOfSecondLine[1]);
// console.log(prevLineItems[j].textContent,"->",textOfItemForFirstWordOfSecondLine,"Diff:", stringDifference);
if(stringDifference < 20 && check == true)
{
check = false;
// stringOutComeOuterLine = prevLineItems[j].textContent +" "+ stringOutComeOuterLine;
stringOutCome = stringOutCome+" "+prevLineItems[j].textContent;
}
else{
if(j<prevLineItems.length-1)
{
console.log(prevLineItems[j+1].textContent);
var previousLineTitleNext = prevLineItems[j+1].title;
var splittedPreviousLineTitleNext = (previousLineTitleNext).split(";");
var previousLineItemFirstSpaceNext = splittedPreviousLineTitleNext[0].indexOf(" ");
var previousLineItemCoordinatesNext = splittedPreviousLineTitleNext[0].slice(previousLineItemFirstSpaceNext);
var previousLineItemCoordinatesListNext = previousLineItemCoordinatesNext.split(' ');
var previousLineDiff = Math.abs(previousLineItemCoordinatesList[3] - previousLineItemCoordinatesListNext[1]);
// console.log("Previous Item",prevLineItems[j].textContent,"->Next Item:",prevLineItems[j+1].textContent,"previousLineDiff:", previousLineDiff);
// console.log("<br> left coordinat: ",previousLineItemCoordinatesList[3]," Right Item: ",previousLineItemCoordinatesListNext[1]);
if(previousLineDiff < 120){
stringOutCome = stringOutCome+" "+prevLineItems[j].textContent;//+" "+prevLineItems[j+1].textContent;
// console.log(stringOutCome,"previousLineDiff:", previousLineDiff);
}
else{
// stringOutComeOuterLine = prevLineItems[j].textContent +" "+ stringOutComeOuterLine;
stringOutCome = stringOutCome +" "+stringOutComeOuterLine;
}
}else{
// console.log("Else Part");
stringOutComeOuterLine = stringOutCome +" "+stringOutComeOuterLine;
}
}
// console.log(stringOutComeOuterLine);
}
}
}
}else{
// stringOutComeOuterLine = lineItems[i].textContent+" "+stringOutComeOuterLine;
// check previousLineitem x
for (var j=0;j<prevLineItems.length;j++)
{
var prevString = prevLineItems[j].textContent;
if (typeof prevString === 'string' && prevString.trim().length > 0)
{
var previousLineTitle = prevLineItems[j].title;
var splittedPreviousLineTitle = (previousLineTitle).split(";");
var previousLineItemFirstSpace = splittedPreviousLineTitle[0].indexOf(" ");
var previousLineItemCoordinates = splittedPreviousLineTitle[0].slice(previousLineItemFirstSpace);
var previousLineItemCoordinatesList = previousLineItemCoordinates.split(' ');
// console.log(prevLineItems[j].textContent,"->",textOfItemForFirstWordOfSecondLine,"Diff:", stringDifference);
if(j<prevLineItems.length-1)
{
console.log(prevLineItems[j+1].textContent);
var previousLineTitleNext = prevLineItems[j+1].title;
var splittedPreviousLineTitleNext = (previousLineTitleNext).split(";");
var previousLineItemFirstSpaceNext = splittedPreviousLineTitleNext[0].indexOf(" ");
var previousLineItemCoordinatesNext = splittedPreviousLineTitleNext[0].slice(previousLineItemFirstSpaceNext);
var previousLineItemCoordinatesListNext = previousLineItemCoordinatesNext.split(' ');
var previousLineDiff = Math.abs(previousLineItemCoordinatesList[3] - previousLineItemCoordinatesListNext[1]);
// console.log("Previous Item",prevLineItems[j].textContent,"->Next Item:",prevLineItems[j+1].textContent,"previousLineDiff:", previousLineDiff);
// console.log("<br> left coordinat: ",previousLineItemCoordinatesList[3]," Right Item: ",previousLineItemCoordinatesListNext[1]);
if(previousLineDiff < 120){
stringOutCome = stringOutCome+" "+prevLineItems[j].textContent;//+" "+prevLineItems[j+1].textContent;
// console.log(stringOutCome,"previousLineDiff:", previousLineDiff);
}
else{
// stringOutComeOuterLine = prevLineItems[j].textContent +" "+ stringOutComeOuterLine;
stringOutCome = stringOutCome +" "+stringOutComeOuterLine;
}
}else{
// console.log("Else Part");
stringOutComeOuterLine = stringOutCome +" "+stringOutComeOuterLine;
}
// console.log(stringOutComeOuterLine);
}
}
}
}
}
console.log(stringOutComeOuterLine);
return stringOutComeOuterLine;
}

How to use external data plot a multi lineseries chart

I am using amcharts4 plugin to plot a multi-lineseries graph.
But the plotted points do not locate at the right position (Blue dot at the edge of y-axe)
Here is the output chart that I get. (pls see the attached above)
Not sure what had done wrong with the following codes. Hope someone can help me out.
Thanks in advance!
var chart = am4core.create("chartdiv", am4charts.XYChart);
//Create axes
var categoryAxis = chart.xAxes.push(new
am4charts.CategoryAxis()); categoryAxis.dataFields.category = "date";
categoryAxis.title.text = "Month-Year";
categoryAxis.title.fontWeight = "bold";
/* Create value axis */
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.title.text = "Total Sales ($)";
valueAxis.title.fontWeight = "bold";
/* Add data */
var ds = new am4core.DataSource();
ds.url = window.location.origin+"/home/salesVolumnVersusPeriod"; //Sample of external JSON DATA = [{"date":"02-2020","FS":6288, 'IO':2342}]
ds.events.on("done", function(ev) {
chart.config = ev.data;
var u = ev.data; var data =
ev.target.data[0]; var datakey = Object.keys(data);
var text = '';
for (var i = 1; i < datakey.length; i++) {
addSeries(datakey[i], u);
text += datakey[i]+' : {'+datakey[i]+'}'+"\n";
}
$('#chartdiv').append('<div id="test">'+text+'</div>');
});
ds.load();
/* Create series */
function addSeries(b, data) {
// Create series
var series = new am4charts.LineSeries();
series.data = data;
series.dataFields.valueY = b;
series.dataFields.categoryX = "date";
series.name = b;
series.strokeWidth = 3;
series.tensionX = 0.7;
series.bullets.push(new am4charts.CircleBullet());
series = chart.series.push(series);
series.events.on("hidden", updateTooltipText);
series.events.on("shown", updateTooltipText);
}
function getToolstipItemValue(text) {
return `[bold]Date {categoryX}[/]
---- `+text;
}
/* Set up tooltip attachment to other series whenever series is hidden */
function updateTooltipText() {
var added = false;
tooltipText = $('#test').text();
chart.series.each(function(series)
{
if (series.visible && !added) {
series.tooltipText = getToolstipItemValue(tooltipText);
added = true;
}
else {
series.tooltipText = "";
}
});
}
/* Add legend */
chart.legend = new am4charts.Legend();
/* Create a cursor */
chart.cursor = new am4charts.XYCursor();
Finally knew what is wrong. It should use chart.data instead of chart.config.
Now the graph works. Hope this could help you too. Cheers!
chart.config = ev.data;

Call truncate function inside .each loop when populating select options?

I'm trying to dynamically populate a select and call a truncate function in the loop... like below. I want to send the option text down to the function, truncate it if it's longer than 20 chars and send it back before it gets added to the option and appended to the select.
$(function() {
for (var i = 0; i < response.option.length; i++) {
var truncatedText = truncate();
var text = response.option[i].name;
truncate(text);
$("select").append("<option>" + truncatedText.text + "</option>");
}
});
function truncate(text) {
var textLength = text.length;
if (textLength > 20) {
text = text.substr(0, 20) + '...';
}
return text;
}
After jsfiddling for a while I landed on a working solution. Is there a more elegant way to do this?
https://jsfiddle.net/kirkbross/pcb0a3Lg/9/
var namesList = ['johnathan', 'tim', 'greggory', 'ashton', 'elizabeth'];
$(function() {
for (var i = 0; i < 5; i++) {
var name = namesList[i];
$('#names').append('<option>' + name + '</option>');
}
var selected_option = $('#names').find('option:selected').val();
var truncated = truncate(selected_option);
$('option:selected').text(truncated.new);
$('#names').change(function(){
var selected_option = $(this).find('option:selected').val();
var truncated = truncate(selected_option);
$('option:selected').text(truncated.new);
});
});
function truncate(selected_option) {
var nameLength = selected_option.length
if (nameLength > 4) {
selected_option = selected_option.substr(0, 4) + '...';
}
return {new: selected_option}
}

Google Apps Script: Server encountered an error. Try again later

I am stuck.. Error is thrown # Line 63 and sometimes at line 50. Both using the appendTableRow() method. I can't find anything wrong.
row3.appendTableCell(entryDesc)
Link to generated file: Link
Execution Transcript: Link
I am new so if you notice any "bad practices" feel free to aim a finger.
// Import data from the Calendar to the timesheet document
function importDataToTS (dateStart,dateFinish,doc) {
if (!dateStart) {
var dateStart = new Date('January 1, 2014');
}
var cal = CalendarApp.getCalendarById('0k2s9lfibn50scj41gcuurovck#group.calendar.google.com')
var events = cal.getEvents(dateStart, dateFinish);
var oldDate = new Date(dateStart.getFullYear(), dateStart.getMonth(), dateStart.getDate() - 1);
var paragraph = "";
var totalHoursWorked = 0
// START --- Text element styles
// Date
var entryDateStyle = {};
entryDateStyle[DocumentApp.Attribute.BOLD] = true;
entryDateStyle[DocumentApp.Attribute.FONT_SIZE] = 18;
// Title
var entryTitleStyle = {};
entryTitleStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
// entryTimes
var entryTimesStyle = {};
entryTimesStyle[DocumentApp.Attribute.BOLD] = true;
entryTimesStyle[DocumentApp.Attribute.FONT_SIZE] = 12;
// entryDescription
var entryDescriptionStyle = {};
entryDescriptionStyle[DocumentApp.Attribute.ITALIC] = true;
entryDescriptionStyle[DocumentApp.Attribute.FONT_SIZE] = 10;
// END --- Text element styles
var entriesTable = doc.appendTable();
Logger.log(entriesTable.getType());
for (var i = 0; i in events; i++) {
var entryDate = events[i].getStartTime();
if (i > 0) {
oldDate = (events[i-1].getStartTime());
}
// If it's a new day add a full width cell
if (entryDate.getDate() > oldDate.getDate()) {
var row1 = entriesTable.appendTableRow();
row1.appendTableCell(shortDate(entryDate,4));
//.setAttributes(entryDateStyle);
}
// Add title, start/end times & hours worked
// Add title, start/end times & hours worked
var entryTitle = events[i].getTitle();
Logger.log(i + ": " + entryTitle);
var entryTimes = shortTime(events[i].getStartTime(),2) + " - " + shortTime(events[i].getEndTime(),2);
Logger.log(i + ": " + entryTimes);
var entryHoursWorked = ((events[i].getEndTime() - events[i].getStartTime())/(1000*60*60)%24) + "hr(s)";
Logger.log(i + ": " + entryHoursWorked);
var row2 = entriesTable.appendTableRow();
row2.appendTableCell(entryTitle);
//.setAttributes(entryTitleStyle);
row2.appendTableCell(entryTimes + "\t\t" + entryHoursWorked);
//.setAttributes(entryTimesStyle);
// Add entry description
var entryDesc = (events[i].getDescription().length > 1) ? events[i].getDescription().toString() : "";
if (entryDesc.length > 1) {
var row3 = entriesTable.appendTableRow();
row3.appendTableCell();
row3.appendTableCell(entryDesc);
//.setAttributes(entryDescriptionStyle);
}
totalHoursWorked += entryHoursWorked;
if (i === (events.length - 1)) {
var lastRow = entriesTable.appendTableRow();
lastRow.appendTableCell("Total Hours: " + totalHoursWorked);
}
}
for (var i = 0; i in entriesTable; i++) {
for (var j = 0; j in entriesTable[i]; j++) {
Logger.log(i + ":" + j + " " + entriesTable[i][j].toString());
}
}
doc.appendTable(entriesTable);
}
shortDate() && shorttTime()
function shortDate(date,n) {
// Returns a date object as "MMMDD";
if (date) {
switch (n) {
case 1:
//Jul6
return Utilities.formatDate(date, "EST", "MMMdd")
break;
case 2:
//Jul 6
return Utilities.formatDate(date, "EST", "MMM dd")
break;
case 3:
//July 6
return Utilities.formatDate(date, "EST", "MMMM dd")
break;
case 4:
return Utilities.formatDate(date, "EST", "EEE, MMM dd")
break;
default:
//Full Date unchanged
return date;
}
}
}
function shortTime(date) {
//Returns time string formatted as "hh:mm"am/pm
//Still needs to be updated with Utilities.formatDate
if (date) {
var hours = (date.getHours() > 12) ? (date.getHours() - 12) : date.getHours();
var ampm = (date.getHours() > 12) ? "pm" : "am";
var minutes = (date.getMinutes() == 0) ? "00" : date.getMinutes();
var time = hours + ":" + minutes + ampm
return time.toString();
}
}
I found a solution, it appears that: body.appendTableCell(); doesn't handle line breaks "\n". When the script was importing a multi-line event description from the calendar I would get a "server error" message. Adding split('\n') to the description row solved the problem. This worked: body.appendTableCell(data).split("\n");
Finished code:
var entryDesc = (events[i].getDescription().length > 1) ? events[i].getDescription() : "";
if (entryDesc) {
var row3 = entriesTable.appendTableRow();
row3.appendTableCell("");
row3.appendTableCell(entryDesc.split("\n"))
.setAttributes(entryDescriptionStyle);
}
I don't have a complete answer but I thought it might be interesting in the mean time to show a version that works without the event description.
I changed the calculation of total time that didn't work either.
Code can be tested on any default calendar using test function.
function test(){
//dateStart,dateFinish,doc
var doc = DocumentApp.getActiveDocument();
var dateStart = new Date('January 1, 2014');
var dateFinish = new Date('April 1, 2014')
importDataToTS (dateStart,dateFinish,doc);
}
function importDataToTS (dateStart,dateFinish,doc) {
if (!dateStart) {
var dateStart = new Date('January 1, 2014');
}
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEvents(dateStart, dateFinish);
var oldDate = new Date(dateStart.getFullYear(), dateStart.getMonth(), dateStart.getDate() - 1);
var paragraph = "";
var totalHoursWorked = 0
// START --- Text element styles
// Date
var entryDateStyle = {};
entryDateStyle[DocumentApp.Attribute.BOLD] = true;
entryDateStyle[DocumentApp.Attribute.FONT_SIZE] = 18;
// Title
var entryTitleStyle = {};
entryTitleStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
// entryTimes
var entryTimesStyle = {};
entryTimesStyle[DocumentApp.Attribute.BOLD] = true;
entryTimesStyle[DocumentApp.Attribute.FONT_SIZE] = 12;
// entryDescription
var entryDescriptionStyle = {};
entryDescriptionStyle[DocumentApp.Attribute.ITALIC] = true;
entryDescriptionStyle[DocumentApp.Attribute.FONT_SIZE] = 10;
// END --- Text element styles
var entriesTable = doc.appendTable();
Logger.log('events.length = '+events.length);
for (var i = 0; i <events.length; i++) {
var entryDate = events[i].getStartTime();
if (i > 0) {
oldDate = (events[i-1].getStartTime());
}
Logger.log('i = '+i);
// If it's a new day add a full width cell
if (entryDate.getDate() > oldDate.getDate()) {
var row1 = entriesTable.appendTableRow();
row1.appendTableCell(shortDate(entryDate,4))
.setAttributes(entryDateStyle);
}
// Add title, start/end times & hours worked
var entryTitle = events[i].getTitle();
var entryTimes = shortTime(events[i].getStartTime(),2) + " - " + shortTime(events[i].getEndTime(),2);
var entryHoursWorked = (events[i].getEndTime().getTime() - events[i].getStartTime().getTime())/(1000*60*60) + "hr(s)";
var row2 = entriesTable.appendTableRow();
row2.appendTableCell(entryTitle)
.setAttributes(entryTitleStyle);
row2.appendTableCell(entryTimes + "\t\t" + entryHoursWorked)
.setAttributes(entryTimesStyle);
// Add entry description
var entryDesc = (events[i].getDescription().length > 2) ? events[i].getDescription() : "";
totalHoursWorked += Number(entryHoursWorked.replace(/\D/g,''));
if (i === (events.length - 1)) {
var lastRow = entriesTable.appendTableRow();
lastRow.appendTableCell("Total Hours: " + totalHoursWorked+' Hours');
}
}
for (var i = 0; i in entriesTable; i++) {
for (var j = 0; j in entriesTable[i]; j++) {
Logger.log(i + ":" + j + " " + entriesTable[i][j].toString());
}
}
doc.saveAndClose();
}