Is it possible to use search.luceneSearch with previously declared vars? - javascript

I want to create a script which will be validated by an action/folder rule in Share.
I was thinking about using previously declared vars, something like these:
var clientsite = "client"
var docfolder = "document_alias"
var docyear = 2015
And my code would be something like this:
var folder = search.luceneSearch(" PATH:\"/app:company_home/st:sites/**clientsite**/**docfolder** \" AND TYPE:\"cm:folder\" AND \#cm\\:name:\"**docyear**\" ");
if (folder == null || folder.length == 0) {
//create new folder called 'docyear'
}
else {
//move to the already existing folder related to 'docyear'
}
Where the bold(I tried to bold items with * in the code, sorry) values would be the vars previously declared.
Is there a way to use vars like in that way??
Thanks!

Sure! You just need to append them, the standard javascript string creation doesn't support template parameters, so take your line
var folder = search.luceneSearch(" PATH:\"/app:company_home/st:sites/**clientsite**/**docfolder** \" AND TYPE:\"cm:folder\" AND \#cm\\:name:\"**docyear**\" ");
And make it something like
var folder = search.luceneSearch(" PATH:\"/app:company_home/st:sites/"+clientsite+"/"+docfolder+" \" AND TYPE:\"cm:folder\" AND \#cm\\:name:\""+docyear+"\" ");

Related

Take variable values and put them in another file

I'm coding the game blockly, I have a variable called lineCount which counts the number of line breaks. however this variable is in a file called lib-dialog.js. When I insert the value of this variable with innerHTML I can get the value of lines by creating a div in the soy.js file (File by which I need to treat the result) But I need this value in a variable to put an if(lines == 6) { }
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
document.getElementById("contarBloco").innerHTML = lineCount;
var contandoBloco = lineCount;
}
I need to take the variable lineCount and put its value in another js.but I'm only managing to insert it into a div with innerHTML
it is better you use localstorage . Set the value of localcount in the local storage and get wherever you want
var lineCount = noComments.split('\n').length;
localStorage.setItem("lineCount", lineCount); // in first file
var count = localStorage.getItem("lineCount") // in second file
with this logic you will get the value but it will be string then for that you either use directly string or convert into integer using parseInt method
parseInt(count);
may be it will help . Thanks
I don't know if your Javascript files are modules, if so, you can return a function in your lib-dialog.js page and return it.
Example
lib-dialog.js =
let Dialog = (function() {
function SetLineCountVariable(LocalLineCount){
LineCount = LocalLineCount;
}
return SetLineCountVariable
})();
And in your soy.js file
let Soy = (function() {
Dialog.SetLineCountVariable(6);
})();
And do not forgot to call your JS file in order in your HTML page
Another way, if you only want the variable result in your another JS file, in your lib-dialog.js, show the result of LineCount in html tag and get it in your another JS file with document.getElementById

How to access the contents of a directory passed in the URL parameters passed to a browser

First off, for Chromecast reasons, I want to, currently, limit the solution to the Chrome browser.
What I'd like to do is package up a directory of images, with a launcher batch file (cmd or sh) and an html file. The html file is to be completely self contained, with no imports.
The bat file would contain something like:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files "file://%CD%\SlideShow1.2.html?slideDir=%CD%\Slides"
Currently I can use
<input type="file" id="slideInput" multiple="multiple" webkitdirectory="webkitdirectory" onchange="appendToSlideList();" accept=".png,.gif,.jpg,.jpeg" />
to manually select files, and
var slideList = [];
var numSlides = 0;
function appendToSlideList()
{
var slideInput = document.getElementById("slideInput");
var slides = slideInput.files;
for(j = 0; j < slides.length; j++)
{
slideList[numSlides++] = slides[j];
}
}
to append pictures from selected directories to the master slide list. Then the following, via a Timer() object displays the slides:
function showNext()
{
if(picture == null)
{
picture = document.getElementById("slideShow");
intervalElem = document.getElementById("interval");
}
if(currentPicture == numSlides)
{
currentPicture = 0;
}
// this comes from https://www.w3.org/TR/file-upload/#file
picture.src = window.URL.createObjectURL(slideList[currentPicture++]);
var interval = parseInt(intervalElem.value) * 1000;
timer = new Timer(showNext, interval);
}
If you've read this far, kudos :). So, all this (plus other auxiliary code that is not germane to the desired solution) works to show a slideshow based on user input from the object.
My desire is to package things up so that all the user has to do is double click on the bat file, and the browser proceeds to show the slide show.
So, after all this, my question is, how do I take the directory passed in, and get all the graphic files in that directory, for use in the already working code.
I've spent the last six hours researching this question, much on StackOverflow, and it appears, to me, currently, that this is an impossible quest.
Here's a fiddle with 'complete' minimalist code: https://jsfiddle.net/hrvrdfjs/
Thanks!
Tom.
There is currently no way for JavaScript in the browser to list files from a directory without the user explicitly choosing the directory in the browser.
However, you can easily create a JavaScript file that contains a list of the image files in the directory from a batch file like this:
#echo off
echo var toC = ` > "C:\slides\data.js"
dir C:\slides\*.png,*.gif,*.jpg,*.jpeg /B >> "C:\slides\data.js"
echo `; >> C:\slides\data.js
This will create file data.js which looks like this:
var toC = `
funny.png
serious.png
holidays.jpeg
`;
Explanations:
echo var toC = ` > "C:\slides\data.js"
Creates or overwrites the file C:\slides\data.js with the javascript code that is the first part of creating a template literal.
dir C:\slides\*.png,*.gif,*.jpg,*.jpeg /B >> "C:\slides\data.js"
Tells dir to list the files with the given extensions in the given directory and appends the file names to the file data.js. The parameter /B makes dir only output the files names, no other information and also skip outputting a header and footer for the listing.
echo `; >> C:\slides\data.js
This appends the end of the javascript template literal.
In JavaScript ES6 and newer, template literals can be used to create string literals that span multiple lines and can contain arbitrary characters.
Load the file data.js dynamically from your html document (by inserting a script tag that refers to the file) and you can access the variable toC which contains the list of files as a multi-line string.
This is a demo where the data.js file is statically included:
<html>
<head>
<script src="C:\slides\data.js"></script>
</head>
<body>
<script>
window.alert(toC);
</script>
</body>
</html>
I wasn't able to use the "dir" command as given above, perhaps because I'm using windows 7. Here is what I came up with, instead:
mkdir C:\Temp\slideShow
rem Replace each instance of a back slash with two, as javascript will remove a single backslash
rem (Unless it is followed by a 'valid' backslash char (r,n,etc.), which is not what we want.).
echo var topLocation = '%CD:\=\\%'; > C:\Temp\slideShow\topLocation.js
echo var slideDirContents = ' > "C:\Temp\slideShow\slideDirContents.js"
dir %CD%\Slides\*.jpeg %CD%\Slides\*.jpg %CD%\Slides\*.png %CD%\Slides\*.gif /B /ON >> "C:\Temp\slideShow\slideDirContents.js"
echo '; >> C:\Temp\slideShow\slideDirContents.js
Then, to split out each file from the input .js file, and create a file path that would later be used to build an URL that the img.src could present the file (NOTE: the add function had to be done after the page was loaded, so the textarea element would be present for the javascript to modify):
function doOnloadFunctions()
{
addStaticsToSlideList();
}
function addStaticsToSlideList()
{
// Empty dir on Windows == size 2 (CR-LF)
// Empty dir on others == size 1 (CR or LF)
if((slideDirContents.length != 2) && (slideDirContents.length != 1))
{
var slidelistElem = document.getElementById("slidelist");
// Linux/Unix/BSD based line separator = \n
// Windows based line separator = \r\n
// Mac based line separator = \r
var re = /\n|\r\n|\r/;
var slides = slideDirContents.split(re);
for(j = 0; j < slides.length; j++)
{
var aFile = {};
var theName = slides[j].trim();
if(theName.length > 0)
{
var fileName = slides[j];
aFile.fileName = topLocation + '\\Slides\\' + fileName;
// Set the original index to the current insertion point.
aFile.oi = numSlides;
// Set the shuffle index simply to instantiate it. We'll
// set the si for real when we want to shuffle the array.
aFile.si = 0;
var listElem = document.createElement("li");
listElem.appendChild(document.createTextNode(fileName));
slidelistElem.appendChild(listElem);
slideList[numSlides++] = aFile;
}
}
}
}
There's a <file> input element that can be used to append local files to the slide list, the <file> input doesn't fill in fileName it just fills in name thus this is the differentiating code that instantiates each <img> with the proper url:
if(!(typeof slideList[currentPicture].fileName === 'undefined' || slideList[currentPicture].fileName === null))
{
// variable is defined and not null
picture.src = "file://" + slideList[currentPicture++].fileName;
}
else
{
// this comes from https://www.w3.org/TR/file-upload/#file
picture.src = window.URL.createObjectURL(slideList[currentPicture++]);
}
Thanks to NineBerry for the code and suggestions!

how to break up the content of a long text file to fit into multiple variables in google apps script?

I have a very long plain text file in my google drive which I need to parse through and select pieces of information through a script. I have successfully pulled out the text and put it into a string variable, but it is so long that the variable only contains about 1/6 of the full document.
This is the code I am using:
function f09ToSpreadsheet() {
var allFilesInFolder,cntFiles,docContent,fileNameToGet,fldr,
thisFile,whatFldrIdToUse;//Declare all variable at once
whatFldrIdToUse = '0B2O23fJ4nQLONlA4RlhuLWp0Y0k';
fileNameToGet = 'Copy of RS_Tionesta_1N.txt';//Assign the name of the file to get to a variable
//Get a reference to the folder
fldr = DriveApp.getFolderById(whatFldrIdToUse);
//Get all files by that name. Put return into a variable
//allFilesInFolder = fldr.getFilesByName(fileNameToGet);
allFilesInFolder = fldr.getFiles();
//Logger.log('allFilesInFolder: ' + allFilesInFolder);
if (allFilesInFolder.hasNext() === false) {
//If no file is found, the user gave a non-existent file name
return false;
};
cntFiles = 0;
//Even if it's only one file, must iterate a while loop in order to access the file.
//Google drive will allow multiple files of the same name.
while (allFilesInFolder.hasNext()) {
Logger.log("yup")
var thisFile = allFilesInFolder.next();
//KEY TO READING TEXT FROM .F05 & .F09 ->
docContent = thisFile.getAs("application/octet-stream");
var string = docContent.getDataAsString();
Logger.log('docContent : ' + string );
};
}
The "string" object, when printed to the log, only contains the first part of the text doc.
Is there any way to, say, split up the document into small pieces and store each part in a variable?
I'm afraid I've not tested this so apologies if it doesn't work straight away but could you get your document paragraph by paragraph and append the text like that?
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paras = body.getParagraphs();
paras.forEach(function( para ){
var text = para.getText();
populateSheet( text );
});

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

JS How to include a variable in a path?

The following variable contains a string that is a path to an image.
iconBlue.image = 'http://www.site.com/icon1.jpg';
How can include a variable in this path? Let me explain more detailed. Lets say there are many icons in a folder icon1.jpg icon2.jpg etc. I have a variable named iconspec that depending on its value (1 or 2 or 3 etc) points to the icon I must use.
How can i include variable iconspec in the path?
iconBlue.image='http://www.site.com/icon"iconspec".jpg
Something like this i guess but with correct syntax.
You just need to put it like a simple string with variable.
In your case, you should do this:
iconBlue.image = 'http://www.site.com/icon'+iconspec+'.jpg';
The + operator is like the . in PHP, it merge string.
iconBlue.image='http://www.site.com/icon'+iconspec+'.jpg';
To take a little different route, you could encapsulate the concatenation in a function and make it a bit more reusable:
var icon = function(){
this.path = '';
this.imageName = '';
this.imagePath = function() { return this.path + '/' + this.imageName };
};
var iconBlue = new icon(),
iconRed = new icon();
iconBlue.path = "c:\\stuff";
iconBlue.imageName = "icon1.jpg";
iconRed.path="c:\\morestuff";
iconRed.imageName = "icon2.jpg";
alert(iconBlue.imagePath());
alert(iconRed.imagePath());
The simplest solution is to use the + to concatenate the variable to the string:
var name = 'sachleen';
var result = 'my name is ' + name;
Output: my name is sachleen
There are a couple of more powerful options available as well.
JavaScript sprintf() is a sprintf implementation for JS.
string.format in JS

Categories

Resources