How to load a random file from a directory - javascript

I am trying to create a question bank on GitHub Pages.
I load a specific file using:
$(document).ready(function() {
var theQuestion = "./questionsBank/"+"question-4"+".html"; //path to load
$("#question").load(theQuestion); //loading the question
});
Now, there are many files in the questionsBank directory and I would like to have a script picking and loading a random one, but I don't know how to do in JS.
How do you retrieve all filenames in questionsBank directory?
I would like to do something like below but don't know how to read filenames in a directory into an array:
var questionFolder = './some directory';
var questionFiles = [];
questionFiles = readingFilesandPopulatingIntoArray(questionFolder); \\how to do this?
var folderSize = questionFiles.length ;
randomNumber = Math.floor(Math.random() * folderSize);
randomQuestion = questionFiles[randomNumber];
$("#question").load(randomQuestion);

As commented by #Lawrence Cherone, the only way of getting the contents of a remote directory is by having an index of it.
Of course Apache has it's own directory scanner, which if configured ok, can render an HTML page with its contents. Then you could fetch that index and loop over the file links in it.
But GitHub Pages does not generates such indexes, so you need to generate it by your own. To do so, you need to do it during the build/deploy process of your page (which we don't know). There, you can add a NodeJS script (or whatever other language you prefer to use, like a plain bash script) using, for example, node's fs dir.read() to get the files list in ./questionsBank/ directory and generating a file to save it somehow (for example, a JSON file containing an Array).
Finally, you can include it directly in your code during the build process by importing it somewhere, or fetching it as you'd fetch any other URL containing a JSON (or whatever other format you decided to use).

Related

In yii2 how to refer a external csv file into java script?

As it is yii2, i cannot refer external file.
my index file in view folder code is :
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"temperatures.csv", // path to CSV file
{} // options
);
</script>
i need to call my temperatures.csv in the same view folder, i don't know how to give the path, any help?
The folder with view templates is not directly accessible in yii2 so there is no way to refer the csv file there from javascript.
The most simple way to deal with it is to put the csv file in the web folder.
For example you can put your csv file to web/data folder. To get the url for the file you can use url helper.
\yii\helpers\Url::to('#web/data/temperatures.csv');
It's better to use the url manager to get the url because it will take care of handling the base url for you, that might be different in different environments. For example final url will probably be /data/temperatures.csv in production but it can be /web/data/temperatures.csv in development.
Another option is to make action that will send the file.
In that case you can leave the temperatures.csv where it is. You need to make a new action in your controller, for example getTemperatures.
public function actionGetTemperatures()
{
$file = \Yii::getAlias('#app/views/controller/temperatures.csv');
return \Yii::$app->response->sendFile($file);
}
Then you will use the url of this action in javascript.
\yii\helpers\Url::to(['controller/get-temperatures']);
The advantage of this solution is, that it allows you to control whether the user is allowed to access the file.

how to fetch/load model.json and weight.bin from two different URL?

I was going through Save and load models- Tensorflow documentation page to load/save and run models into browser. CDN version of tensorflow.js is 1.1.2
Syntax to use for example
const model = await tf.loadLayersModel('http://model-server.domain/download/model.json');
The documentation says:
This loads a model from an http endpoint. After loading the json file the function will make requests for corresponding .bin files that the json file references.
But the system i am working doesn't allow two different file to have the same URL path, as each file is saved with an individual id.
So my question is, how can I load/save the model.json and the weight.bin (https method) from two different URL addresses?
Btw if tf.loadFrozenModel (modelUrl, weightsManifestUrl, requestOption?) could be used,then please let me know how to use it? Because, it did not work for me.
If you want to load the model and the weights from 2 different locations, according to the doc, the following can be used:
const model = await tf.loadLayersModel('http://model-server.domain/download/model.json', {weightPathPrefix: weigthsUrl});

jQuery AJAX Cannot Find Local File in WordPress Installation

I'm having trouble with a WordPress plugin I've been working on. A JS file is loaded as a resource with each page/post opened, which in turn has a request to load the contents of an HTML file.
Being that the page/post directories change frequently, I'm having a difficult time making the jQuery dynamically pin down the location of the file (even though it's in the same location as the rest of the plugin resources).
An example:
jQuery('body').append('<section id="asub00LOAD"></section>');
var url = jQuery(location).attr('hostname');
var dir = url + '/wp-content/plugins/adsenseunblock/html/adunblock.html #asub00AJAX';
jQuery('#asub00LOAD').load(dir);
That was placing the whole URL path to the file after the local install ("root.com/CHEETOS/" in this case):
After which, I did this, which works fine for the root directory only:
jQuery('body').append('<section id="asub00LOAD"></section>');
var dir = 'wp-content/plugins/adsenseunblock/html/adunblock.html #asub00AJAX';
jQuery('#asub00LOAD').load(dir);
After you venture to another page, obviously the directory location is wrong again.
I tried to place some PHP into my JS file before so I could take advantage of the $plugins_url feature, but that became very convoluted and it's hard to track any errors without a PHP console to work from...
I hope someone here will have a solution for me!
The first example probably fails because there's no http:// (or //)
Use var url = "//" + location.hostname;
The second example should work everywhere if you use a root-relative path:
var dir = '/wp-content/plugins/adsenseunblock/html/adunblock.html #asub00AJAX';

Google Apps Script/ Drive API (Javascript) Remove from Shared With Me

Does anyone have any suggestions for how to remove a file from shared with me? I need to do this without actually revoking access, as the people are added via a contact group, so only removing 1 person will not work.
Things to note:
I know using this can find the file:
var files = DriveApp.searchFiles('sharedWithMe');
//then I set file = what I'm looking for.
However, this will not remove the file from shared with me:
DriveApp.removeFile(file);
I've also tried brute forcing by patching the metadata, except it was to no avail.
In addition, it is wrong to assume that shared with me is a folder, as when listing parent folders the file returns nothing.
Only DriveApp cannot completely remove files. So it is necessary to use Drive API. "removeFile()" is used for changing parent folder information. It cannot remove files. I prepared 2 samples for removing files. If you are owner of the file, you can remove it.
Move file to trash box and empty trash :
var file = DriveApp.getFilesByName("filename").next();
file.setTrashed(true)
Drive.Files.emptyTrash();
Remove directly file :
Drive.Files.remove("fileID");
It was confirmed that above script can remove file even if other users are using.
For using above script, it is necessary to enable Drive API at Advanced Google Services and Drive API at https://console.developers.google.com/ Developers Console Project.
Files without parent folder :
If you had used "removeFile()", files without the parent folder may be existing in your drive. You can confirm them following script. This can retrieve file name and file ID of files without the parent folder.
var result = [];
var files = DriveApp.getFiles();
while (files.hasNext()) {
file = files.next();
if (!file.getParents().hasNext()) {
result.push([file, file.getId()]);
}
}
Logger.log(result);

Reading an XML resource file in a Javascript WinRT app

I'm trying to set up a config file for some app-specific items (such as API keys) for my WinRT experiment.
So far I added a "config.xml" file to the root of my project, marked it as a resource in the properties... and then I'm stuck.
Every example I can find seems to deal with JSON resource files (which are somehow tied to localization by convention and don't seem to be appropriate for general config stuff?), loading files from disk (which doesn't work since resources get compiled into the .pri file), or uses C#.
So how can I make this work in my Javascript/HTML5 app?
My latest attempt was this:
var uri = new Windows.Foundation.Uri('ms-resource:///config');
var xml = Windows.ApplicationModel.Resources.ResourceLoader
.getStringForReference(uri);
but this doesn't work and throws the following exception:
0x80073b1f - JavaScript runtime error: ResourceMap Not Found.
What am I missing?
I feel like I'm getting closer:
var r = Windows.ApplicationModel.Resources.Core.ResourceManager
.current.mainResourceMap.lookup('Files/config.xml');
var candidates = r.resolveAll();
candidates[0].getValueAsFileAsync().done(readXml);
This finds the file resource, but all the candidate contains is the original absolute path to the file, so getValueAsFileAsync() throws an exception saying "The system cannot find the file specified." (and the readXml callback isn't called).
So I still can't seem to get at the contents of this XML file.
Try this...
var uri = new Windows.Foundation.Uri('ms-appx:///myFolder/myConfig.xml');
var file = Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri);
You can now use the file to parse and handle the data as needed.

Categories