Javascript can't write to a file - javascript

I want the code to write datalogs to JStest.csv file after 5 clicks done by the user are completed, and I have created a CSV file call JStest in the Downloads folder. But when I run my code, it says it can't find this file. Please help !
This is the error message I got:
Error: ENOENT: no such file or directory, open '/Downloads/JStest.csv'
Here's my code:
const app = require('electron').remote.app;
const fileDir = app.getPath('desktop');
const path = require("path");
var fs = require('fs');
// this will hold all the data we need
var dataLog = "";
// this will count how many clicks have occured
var clicks = 0;
var maxTrials = 5;
var iconArray = document.getElementById("iconDrawer");
// reference our start button
var startButton = document.getElementById("startBtn");
// display how many tasks a user has completed
var counterDisplay = document.getElementById("counter");
// display the target icon to click (find the element with this HTML tag)
var indicator = document.getElementById("indicator");
// element that holds all your icons
var parent = document.getElementById("iconDrawer");
// array of all icons (hint: use the parent var to reference its children icons)
var icons = parent.children;
var i0 = icons[0];
var i1 = icons[1];
var i2 = icons[2];
var i3 = icons[3];
var i4 = icons[4];
/////////////////////////////////////////////////////////////////////////////////////
// TODO: Set the filepath, so you know where the .csv file is going!
/////////////////////////////////////////////////////////////////////////////////////
function save()
{
// change the filepath in the writeFile() function
fs.writeFile( path.resolve(fileDir, "/Users/lidaochang/Desktop/Downloads/JStest.csv"), dataLog, (err) => {
if (err) alert(err);
alert("all tasks are done");
});
}
function randomIcon()
{
// Generate a random number in the appropriate range
var iconIndex = Math.random()*4;
iconIndex = Math.round(iconIndex);
return iconIndex;
}
var timedClick = function()
{
// disables the start button, so user can't press it twice
//startButton.onclick = function(){};
// call randomIcon function to get random index and the matching icon
var targetIndex = randomIcon();
var targetIcon = icons[targetIndex];
indicator.src = targetIcon.src;
// start timing right here
var startTime = performance.now();
// this is where we are going to start watching for clicks on icons
// this loop will add an onclick function to each icon
for(var i=0; i < icons.length; i++)
{
icons[i].onclick = function()
{
// everything in here will occur when an icon is pressed
// stop timing and record how long it took
// calculate time elapsed
// record whole milliseconds
var endTime = performance.now();
var timeTaken = endTime - startTime;
timeTaken = Math.round(timeTaken);
alert("that took " + timeTaken);
// only 1 icon can be clicked at a time, so disable all the onclicks now!
// loop through all the icons and disable the function like we did with the start button
for(var j=0; j < icons.length; j++) {
if (j != targetIcon)
icons[j].onclick = function(){};
}
// record the time and positions of the target icon and the icon the user actually pressed
// this is to be stored in a new line in the 'dataLog' variable
// append to the 'dataLog' variable
var iconClicked = this.id[1]; // INCLUDE THIS
var data = "";
data.concat(i, " ", targetIndex, " ", iconClicked, " ", timeTaken);
// add to the end of the 'dataLog' variable as explained above
dataLog += data;
// increment clicks completed
clicks += 1;
// update what the counterDisplay says!
// modify the innerHTML property of counterDisplay
// it shows the user how many clicks have currently been completed
counterDisplay.innerHTML = clicks + " tasks out of 5 completied";
// if maxTrials is reached, then data collection is over, so call save and reset 'clicks' and 'dataLog'
if (clicks == maxTrials) {
save();
clicks = 0;
dataLog = "";
}
to starting the trial
startButton.onclick = timedClick;
}
}
}
window.onload = function()
{
startButton.onclick = timedClick;
}

Related

Create calendar event from Gmail?

I found the following code online but can't remember where I got it from. The script will search for any emails with a specific label (in this case "GReminder") and add those emails into your calendar. I tried to set this up but I'm getting the error message:
TypeError: label.getThreads is not a function
I'm not familiar with Javascript and I'm not a software developer by any means. I've tried to modify it but couldn't get it to work. Hoping someone can help me here. Here is the code below:
function gMailReminder() {
var reminderLabel = "GReminder", //Substitute your label here
calendarName = "Mobile Calendar", ////Substitute your Calendar name here
reminderDuration = 2, //duration in hours
label = GmailApp.getUserLabelByName(reminderLabel),
threads = label.getThreads();
if (threads.length > 0) {
//get calendar by name
var cals = CalendarApp.getCalendarsByName(calendarName);
var now = new Date().getTime();
for (i in threads) {
cals[0].createEvent(reminderLabel + '- '+threads[0].getFirstMessageSubject(),
new Date(now+(60000*60*reminderDuration)),
new Date(now+(60000*60*reminderDuration)), {description: threads[i].getPermalink()});
}
//Remove the label from the mails to avoid duplicate event creation on next run
label.removeFromThreads(threads);
}
}
Furthermore, the code searches for the label "GReminder" and then removes that label at the end of the script. I'd like to modify this so that the script searches for GReminder in Gmail, then adds a new GReminder-Processed label to it (to show that those emails have been "processed") and then the next time it runs again, it will skip emails with GReminder-Processed. I've only gotten the part of creating the labels sorted (I think), but can't figure out the rest...
function getOrCreateLabel(labelName) {
var label = GmailApp.getUserLabelByName(labelName);
if (label == null) {
label = GmailApp.createLabel(labelName);
}
return label;
}
var label = getOrCreateLabel("Bill Reminder - processed");
thread.addLabel(label);
function gMailReminder() {
const rlbl = "GReminder";
const rdur = 2;
const label = GmailApp.getUserLabelByName(rlbl);
const threads = label.getThreads();
const cal = CalendarApp.getCalendarsByName("Mobile Calendar")[0];
if (threads.length > 0) {
threads.forEach(t => {
let now = new Date().getTime();
cal.createEvent(rlbl + '- ' + t.getFirstMessageSubject(), new Date(now), new Date(now + (60000 * 60 * rdur)), { description: t.getPermalink() });
});
label.removeFromThreads(threads);
}
}
I think probably your label name is wrong:
Here's a function to get your label names:
function getUserLabels() {
const labels = GmailApp.getUserLabels();
let html = '';
labels.forEach(l => {
html += `<br>Name: ${l.getName()}`
});
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),'Label Names');
}
I modified your code to test the label names:
function gMailReminder() {
const rlbl = "Qs/Services/Google";
const label = GmailApp.getUserLabelByName(rlbl);
const threads = label.getThreads();
let html ='';
if (threads.length > 0) {
threads.forEach(t => {
html += `<br>${t.getFirstMessageSubject()}`;
});
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),'Subjects');
}
}
And this now works
Came up with the solution myself.
As you can see, my label has Chinese characters and GmailApp.Search has no problem with this.
However, LABEL_DONE requires you to put in I guess the unicode (or whatever it's called) of the Chinese characters. Again, I don't know anything about Javascript and so a lot of my code is just copying and pasting code from somewhere else and modifying them to the best of my extent. I had to do a bit of debugging to find out what my Chinese label looks like in the Logger. The result provided by the Logger is the unicode that you see for LABEL_DONE. If you also use non-English characters for your labels, you'll need to test it yourself and find what the corresponding unicode string is.
Anyway, the code below will use GmailApp.Search to search for specific labels (you can mix and match search conditions in there and can test this easily in Gmail search itself). It will then add the emails for those specific labels into Google Calendar, then apply a "Bill Reminder - Processed" label. The next time the Google App Script trigger runs, it will skip these emails, because of the Processed label.
// https://stackoverflow.com/questions/12377640/printing-to-the-console-in-google-apps-script
function testLog(){
Logger.log("Logger.log");
console.log("console.log")
}
function BillReminder_Rates() {
if (!GmailApp) return; // Skip script execution if GMail is currently not available (yes this happens from time to time and triggers spam emails!)
var reminderLabel = "電費,-水費,-垃圾袋,-網路-bill-reminder---processed", //Substitute your label here
calendarName = "Reminders", ////Substitute your Calendar name here
reminderDuration27Days = 648; //duration in hours;
var threads = GmailApp.search('(label:電費,-水費,-垃圾袋,-網路-council-rates---me) AND (-label:電費,-水費,-垃圾袋,-網路-bill-reminder---processed)');
if (threads.length > 0) {
//get calendar by name
var cals = CalendarApp.getCalendarsByName(calendarName);
var now = new Date().getTime();
for (i in threads) {
//cals[0].createEvent(reminderLabel + ' - '+threads[i].getFirstMessageSubject(),
cals[0].createEvent(threads[i].getFirstMessageSubject(),
new Date(now+(60000*60*reminderDuration27Days)),
new Date(now+(60000*60*reminderDuration27Days)), {description: threads[i].getPermalink()});
}
LABEL_DONE = "\u96fb\u8cbb, \u6c34\u8cbb, \u5783\u573e\u888b, \u7db2\u8def/Bill Reminder - Processed";
var label_done = GmailApp.getUserLabelByName(LABEL_DONE);
for (var t in threads) {
var threadblah = threads[t];
// Grab the task data
var taskTitle = threadblah.getFirstMessageSubject();
// Insert the task
//addTask_(taskTitle, TASKLIST);
// Set to 'done' by exchanging labels
//threadblah.removeLabel(label_pending);
threadblah.addLabel(label_done);
}
}
}
function BillReminder_Power_Gas() {
if (!GmailApp) return; // Skip script execution if GMail is currently not available (yes this happens from time to time and triggers spam emails!)
var reminderLabel = "電費,-水費,-垃圾袋,-網路-bill-reminder---processed", //Substitute your label here
calendarName = "Reminders", ////Substitute your Calendar name here
reminderDuration12Days = 288; //duration in hours;
var threads = GmailApp.search('(label:電費,-水費,-垃圾袋,-網路-power -OR label:電費,-水費,-垃圾袋,-網路-gas) AND (-label:電費,-水費,-垃圾袋,-網路-bill-reminder---processed)');
if (threads.length > 0) {
//get calendar by name
var cals = CalendarApp.getCalendarsByName(calendarName);
var now = new Date().getTime();
for (i in threads) {
//cals[0].createEvent(reminderLabel + ' - '+threads[i].getFirstMessageSubject(),
cals[0].createEvent(threads[i].getFirstMessageSubject(),
new Date(now+(60000*60*reminderDuration12Days)),
new Date(now+(60000*60*reminderDuration12Days)), {description: threads[i].getPermalink()});
}
LABEL_DONE = "\u96fb\u8cbb, \u6c34\u8cbb, \u5783\u573e\u888b, \u7db2\u8def/Bill Reminder - Processed";
var label_done = GmailApp.getUserLabelByName(LABEL_DONE);
for (var t in threads) {
var threadblah = threads[t];
// Grab the task data
var taskTitle = threadblah.getFirstMessageSubject();
// Insert the task
//addTask_(taskTitle, TASKLIST);
// Set to 'done' by exchanging labels
//threadblah.removeLabel(label_pending);
threadblah.addLabel(label_done);
}
}
}
function BillReminder_Water() {
if (!GmailApp) return; // Skip script execution if GMail is currently not available (yes this happens from time to time and triggers spam emails!)
var reminderLabel = "電費,-水費,-垃圾袋,-網路-bill-reminder---processed", //Substitute your label here
calendarName = "Reminders", ////Substitute your Calendar name here
reminderDuration15Days = 360; //duration in hours;
var threads = GmailApp.search('(label:電費,-水費,-垃圾袋,-網路-watercare---me) AND (-label:電費,-水費,-垃圾袋,-網路-bill-reminder---processed)');
if (threads.length > 0) {
//get calendar by name
var cals = CalendarApp.getCalendarsByName(calendarName);
var now = new Date().getTime();
for (i in threads) {
//cals[0].createEvent(reminderLabel + ' - '+threads[i].getFirstMessageSubject(),
cals[0].createEvent(threads[i].getFirstMessageSubject(),
new Date(now+(60000*60*reminderDuration15Days)),
new Date(now+(60000*60*reminderDuration15Days)), {description: threads[i].getPermalink()});
}
LABEL_DONE = "\u96fb\u8cbb, \u6c34\u8cbb, \u5783\u573e\u888b, \u7db2\u8def/Bill Reminder - Processed";
var label_done = GmailApp.getUserLabelByName(LABEL_DONE);
for (var t in threads) {
var threadblah = threads[t];
// Grab the task data
var taskTitle = threadblah.getFirstMessageSubject();
// Insert the task
//addTask_(taskTitle, TASKLIST);
// Set to 'done' by exchanging labels
//threadblah.removeLabel(label_pending);
threadblah.addLabel(label_done);
}
}
}
function delete_events()
{
//take care: Date function starts at 0 for the month (January=0)
//{search: 'cycle'+"*"+'Checkpoint'} hier zijn de search terms
var fromDate = new Date(2021,6,1,0,0,0); //This is July 1, 2021
var toDate = new Date(2021,11,1,0,0,0); //This is September 1, 2021 at 00h00'00"
var calendarName = 'Reminders';
var toRemove = 'title_of_the_events';
var calendar = CalendarApp.getCalendarsByName(calendarName)[0];
var events = calendar.getEvents(fromDate, toDate,{search: toRemove});
for(var i=0; i<events.length;i++)
{
var ev = events[i];
if(ev.getTitle()==toRemove) //check if the title matches
{
Logger.log('Item '+ev.getTitle()+' found on '+ev.getStartTime()); // show event name and date in log
ev.deleteEvent(); //uncomment this line to actually do the delete !
}
}
}
function delete_events2()
{
var fromDate = new Date(2021,8,1,0,0,0);
var toDate = new Date(2021,11,27,0,0,0);
var calendarName = 'Reminders';
// delete from Jan 1 to end of Jan 4, 2013 (for month 0 = Jan, 1 = Feb...)
var calendar = CalendarApp.getCalendarsByName(calendarName)[0];
var events = calendar.getEvents(fromDate, toDate);
for(var i=0; i<events.length;i++){
var ev = events[i];
Logger.log(ev.getTitle()); // show event name in log
ev.deleteEvent();
}
}

Photoshop Scripting JavaScript loop through layers problem

I have a script that does the following:
loops through layers,
saves each layer in a separate folder (name of folder same as layer name)
saved layer images have names "nameofthedocument, nameofthelayer.png"
Now I wanted to add text item on top of those layers while they are saving as separate pngs so that for gods sake you don't have to always look at the file name but instead there would be text in the PNG image rasterized and says "nameofthelayer" variable.
So for each layer of course different text should be inserted in the image.
i encountered weird problems once I tried to do that what seamigly looked easy.
HEre is the link with a video and an explanation of the code as well as what I did and why it messed up the script.
https://drive.google.com/drive/folders/1h2KAiEuruLY_PQ2JVhQAwINDYPvk9xHS?usp=sharing
Thank you folks, please help me out
Code, image and video explanation is all available in the link
CODE:
// NAME:
// SaveLayers
// DESCRIPTION:
// Saves each layer in the active document to a PNG or JPG file named after the layer.
// These files will be created in the current document folder.
// REQUIRES:
// Adobe Photoshop CS2 or higher
// VERSIONS:
// 27 March 2013 by Robin Parmar (robin#robinparmar.com)
// preferences stored in object
// auto-increment file names to prevent collisions
// properly handles layer groups
// header added
// code comments added
// main() now has error catcher
// counts number of layers
// many little code improvements
// 26 Sept 2012 by Johannes on stackexchange
// original version
// enable double-clicking from Finder/Explorer (CS2 and higher)
#target photoshop
app.bringToFront();
//alert(activeDocument.name);
function main() {
// two quick checks
if(!okDocument()) {
alert("Document must be saved and be a layered PSD.");
return;
}
var len = activeDocument.layers.length;
// user preferences
prefs = new Object();
prefs.fileType = "";
prefs.fileQuality = 0;
prefs.filePath = app.activeDocument.path;
prefs.count = 0;
saveLayers(activeDocument);
//toggleVisibility(activeDocument);
}
function saveLayers(ref) {
var len = ref.layers.length;
// rename layers top to bottom
for (var i = 0; i < len; i++) {
var layer = ref.layers[i];
if (layer.typename == 'LayerSet') {
// recurse if current layer is a group
saveLayers(layer);
} else {
// otherwise make sure the layer is visible and save it
layer.visible = true;
saveImage(layer.name);
layer.visible = false;
}
}
}
function getNameWithoutExtension(nameWithExt) {
var nameWithoutExtension = nameWithExt;
return nameWithoutExtension.split(".")[0];
}
function saveImage(layerName) {
var f = new Folder("D:/Process/0/"+layerName);
f.create();
//////////////// BROKEN PART I ADDED
#target photoshop
// Current layer name as text layer
var myDoc = app.activeDocument;
var myRulers = app.preferences.rulerUnits
app.preferences.rulerUnits = Units.PIXELS;
var OriginalLayerName = myDoc.activeLayer.name
var myLayerName = myDoc.activeLayer.name + "text";
var myLayerText = myDoc.artLayers.add()
myLayerText.kind = LayerKind.TEXT
var myText = myLayerText.textItem
myColor = new SolidColor
myColor.rgb.red = 255
myColor.rgb.green = 0
myColor.rgb.blue = 0
myLayerText.textItem.color = myColor
myText.position = [0,20] // Upper Left
myText.justification = Justification.LEFT
myText.size = 12
myText.contents = myLayerName
myLayerText.name = myLayerName // Or add a fixed string in quotes i.e. 'My Great Layer Name!'
app.preferences.rulerUnits = myRulers
//////////////////////////////END OF THE BROKN PART
//var handle = generateName(f.path + "/",layerName, ".png");
//alert(handle);
var handle = getUniqueName(prefs.filePath + "/"+ layerName +"/"+ getNameWithoutExtension(activeDocument.name) + ", " + layerName);
//alert(handle);
prefs.count++;
if(prefs.fileType=="PNG") {
SavePNG(handle);
} else {
SaveJPEG(handle);
}
}
function getUniqueName(fileroot) {
// form a full file name
// if the file name exists, a numeric suffix will be added to disambiguate
var filename = fileroot;
for (var i=1; i<100; i++) {
var handle = File(filename + "." + prefs.fileType);
if(handle.exists) {
filename = fileroot + "-" + padder(i, 3);
} else {
return handle;
}
}
}
function padder(input, padLength) {
// pad the input with zeroes up to indicated length
var result = (new Array(padLength + 1 - input.toString().length)).join('0') + input;
return result;
}
function SavePNG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
function SaveJPEG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
// file type
var saveOpt = [];
saveOpt[0] = "PNG";
saveOpt[1] = "PNG";
// png type
var pngtypeOpt = [1];
pngtypeOpt[0]=24;
pngtypeOpt[1]=24;
function okDocument() {
// check that we have a valid document
if (!documents.length) return false;
var thisDoc = app.activeDocument;
var fileExt = decodeURI(thisDoc.name).replace(/^.*\./,'');
return fileExt.toLowerCase() == 'psd'
}
function wrapper() {
function showError(err) {
alert(err + ': on line ' + err.line, 'Script Error', true);
}
try {
// suspend history for CS3 or higher
if (parseInt(version, 10) >= 10) {
activeDocument.suspendHistory('Save Layers', 'main()');
} else {
main();
}
} catch(e) {
// report errors unless the user cancelled
if (e.number != 8007) showError(e);
}
}
function generateName(filePath, layerName, ext) {
var generatedName = app.activeDocument.name;
var generatedName = generatedName.split(".")[0];
generatedName = generatedName + ", " + layerName;
return filePath + generatedName + ext;
}
wrapper();

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

Google Apps Script: How to get this code run after UI is closed?

This may seem a very newbie question, but I'm stuck with it. I've got this code to show a check list in a UI and insert the paragraphs of one or more documents into another target document:
var fact_list = [ ["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles’ Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"] ];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
ScriptProperties.setProperties({'theses': itemsSelected}, true);
app.close();
return app;
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
// Logger.log(j + " : " + type);// to see targetDoc's content
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
But when I call these functions inside my main function, I got a red message (in my language): service not available: Docs and, after the UI from showList() is closed, nothing more happens with my code (but I wanted the main functions continues to run). I call these functions this way:
if (theses == 1){
showList();
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
}
showURL(docName, link); // Shows document name and link in UI
So, how can I fix that? How can I get the code run until the line showURL(docName, link);?
showList();
This function creates only Ui.
You are setting the script properties only in the Server Handler which executes on the click of submit button. Since then:
ScriptProperties.getProperty('theses');
will hold nothing. So you need to call these lines:
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
Inside server handler or put them inside a method and call the method from the server Handler.

How to Increase the numurical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row

How to increase the numerical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row? Data loads from firebase in tabular form.
Fiddle here, so you can understand it much better.
The script which loads (callback) data from firebase is given bellow
var LEADERBOARD_SIZE = 10;
var get_title = $('title').html();
var get_id = $('id').find('textarea').html();
// Create our Firebase reference
var scoreListRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
// Keep a mapping of firebase locations to HTML elements, so we can move / remove elements as necessary.
var htmlForPath = {};
// Helper function that takes a new score snapshot and adds an appropriate row to our leaderboard table.
function handleScoreAdded(scoreSnapshot, prevScoreName) {
var newScoreRow = $("");
newScoreRow.append($("").append($("").text(scoreSnapshot.val().name)));
newScoreRow.append($("").text(scoreSnapshot.val().url));
newScoreRow.append($("").text(scoreSnapshot.val().score));
// Store a reference to the table row so we can get it again later.
htmlForPath[scoreSnapshot.name()] = newScoreRow;
// Insert the new score in the appropriate place in the table.
if (prevScoreName === null) {
$("#leaderboardTable").append(newScoreRow);
} else {
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
}
// Helper function to handle a score object being removed; just removes the corresponding table row.
function handleScoreRemoved(scoreSnapshot) {
var removedScoreRow = htmlForPath[scoreSnapshot.name()];
removedScoreRow.remove();
delete htmlForPath[scoreSnapshot.name()];
}
// Create a view to only receive callbacks for the last LEADERBOARD_SIZE scores
var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);
// Add a callback to handle when a new score is added.
scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
handleScoreAdded(newScoreSnapshot, prevScoreName);
});
// Add a callback to handle when a score is removed
scoreListView.on('child_removed', function (oldScoreSnapshot) {
handleScoreRemoved(oldScoreSnapshot);
});
// Add a callback to handle when a score changes or moves positions.
var changedCallback = function (scoreSnapshot, prevScoreName) {
handleScoreRemoved(scoreSnapshot);
handleScoreAdded(scoreSnapshot, prevScoreName);
};
scoreListView.on('child_moved', changedCallback);
scoreListView.on('child_changed', changedCallback);
// When the user presses enter on scoreInput, add the score, and update the highest score.
$("#scoreInput").keypress(function (e) {
if (e.keyCode == 13) {
var newScore = ($("#scoreInput").val());
var url1 = $("#urlInput").val();
var name = $("#nameInput").val();
$("#scoreInput").val("");
if (url1.length === 0)
if (name.length === 0) return;
var userScoreRef = scoreListRef.child(name);
// Use setWithPriority to put the name / score in Firebase, and set the priority to be the score.
userScoreRef.setWithPriority({
name: name,
url: url1,
score: newScore
}, newScore);
alert('Alternate Link for this App has been Succesfully submitted by you. By using this service you agree that you will Not Spam or Submit Links which refers to illegal or Copyrighted content.');
}
});
// delay function to make link clickable after 4 sec and also add onclick='HitCounter()' into links
var delay = 4000 //4 seconds
setTimeout(function () {
function replaceURLWithHTMLLinks(text) {
var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&##\/%?=~_()|!:,.;]*[-a-z0-9+&##\/%=~_()|])/ig;
return text.replace(re, function (match, lParens, url) {
var rParens = '';
lParens = lParens || '';
var lParenCounter = /\(/g;
while (lParenCounter.exec(lParens)) {
var m;
if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) {
url = m[1];
rParens = m[2] + rParens;
}
}
return lParens + "" + url + "" + rParens;
});
}
var elm = document.getElementById('leaderboardTable');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);
$(document).ready(function () {
$("a[href^='http://']").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
});
}, delay)
and the script which take care of URL Hit Counts is given bellow
function HitCounter() {
var get_id = $('id').find('textarea').html();
var HitCounterRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
var hits = $(tbody).find('tr').children('td').html();
if (hits == null) {
hits = 1;
} else {
hits++;
}
HitCounterRef.setWithPriority({
score: hits
}, hits);
};
I need some modification or improvement in this code so that when some one click on a link then correct corresponding 3rd column of same row should get a increment/increase in it's numerical value.
I also need something which could create connection b/w HitCounter and urls given in 2nd column of every row or initiate the HitCounter function when some one click on any of the link given in 2nd column of every row.

Categories

Resources