I am converting one layout to html; once I make the changes in code/html/css, every time I have to hit F5. Is there any simple javascript/jQuery solution for this? I.e. after I add the script, reload the whole page every 5 seconds (or some other specific time).
<meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html">
If it has to be in the script use setTimeout like:
setTimeout(function(){
window.location.reload(1);
}, 5000);
To reload the same page you don't need the 2nd argument. You can just use:
<meta http-equiv="refresh" content="30" />
This triggers a reload every 30 seconds.
For auto reload and clear cache after 3 second you can do it easily using javascript setInterval function. Here is simple code
$(document).ready(function() {
setInterval(function() {
cache_clear()
}, 3000);
});
function cache_clear() {
window.location.reload(true);
// window.location.reload(); use this if you do not remove cache
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Auto reload page and clear cache</p>
and you can also use meta for this
<meta http-equiv="Refresh" content="5">
setTimeout(function () { location.reload(1); }, 5000);
But as development tools go, you are probably better off with a tab reloading extension.
There's an automatic refresh-on-change tool for IE. It's called ReloadIt, and is available at http://reloadit.codeplex.com . Free.
You choose a URL that you'd like to auto-reload, and specify one or more directory paths to monitor for changes. Press F12 to start monitoring.
After you set it, minimize it. Then edit your content files. When you save any change, the page gets reloaded. like this:
Simple. easy.
Answer provided by #jAndy should work but in Firefox you may face problem, window.location.reload(1); might not work, that's my personal experience.
So i would like to suggest:
setTimeout(function() { window.location=window.location;},5000);
This is tested and works fine.
A decent alternative if you're using firefox is the XRefresh plugin. It will reload your page everytime it detect the file has been modified. So rather than just refreshing every 5 seconds, it will just refresh when you hit save in your HTML editor.
Alternatively there's the application called LiveReload...
If you are developing and testing in Firefox, there's a plug-in called "ReloadEvery" is available, which allows you to reload the page at the specified intervals.
This will work on 5 sec.
5000 milliseconds = 5 seconds
Use this with target _self or what ever you want and what ever page you want including itself:
<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 5000);
}
</script>
<body onload="load()">
Or this with automatic self and no target code with what ever page you want, including itself:
<script type="text/javascript">
function load()
{
setTimeout("location.href = 'http://YourPage.com';", 5000);
}
</script>
<body onload="load()">
Or this if it is the same page to reload itself only and targeted tow hat ever you want:
<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 5000);
}
</script>
<body onload="load()">
All 3 do similar things, just in different ways.
function reload() {
document.location.reload();
}
setTimeout(reload, 5000);
Related
I am using SymPy with PyScript so I cannot use init_printing() in my code as I am not running code cell by cell. How can I still use pprint to make my output look good in Web?
Output I am getting:
Output I am expecting:
I wrote a MathJax example that displays formulas correctly: link Right-click on the page to view the source code.
The key is that you must tell MathJax to typeset the answer. This requires dropping down to JavaScript for a simple two line call:
<script>
function draw(str) {
var math = MathJax.Hub.getAllJax("MathDiv")[0];
MathJax.Hub.Queue([ "Text", math, str ]);
}
</script>
Example code including initializing MathJax and setting up the display DIV:
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<div id="MathDiv">\({}\)</div>
<py-script>
delta__y_l = symbols('Delta__y_l')
latexstr = latex(delta__y_l)
js.draw(latexstr)
</py-script>
Is there ever a way possible to get the actual creation / modification time of the file being uploaded, using JavaScript?
As for PHP, using filectime() and filemtime(), it only shows the date / time the file is uploaded, and not the time the file is actually created / modified on the source.
In short, what I want is to check the m-time of a file before/during/after upload (where-ever possible) and decide whether or not to store the file on the server, and report the same back to the client.
If you're talking about the file date/time on the user's machine, you can get that via the File API (support), which provides lastModified, which is the date/time as a number of milliseconds since The Epoch (if you want a Date, you can pass that into new Date). (There's also the deprecated lastModifiedDate, but that is deprecated and not supported on Safari [at least].) The File API is universally supported in modern browsers (the particular feature you'd be using is the File object). You'd get the value from the File object and include that information in a separate (for instance, hidden) field.
Here's a rough-but-complete example of reading the last modified date (live copy):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Modified</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileModified() {
var input, file;
// Testing for 'function' is more specific and correct, but doesn't work with Safari 6.x
if (typeof window.FileReader !== 'function' &&
typeof window.FileReader !== 'object') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('filename');
if (!input) {
write("Um, couldn't find the filename element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Show Modified'");
}
else {
file = input.files[0];
write("The last modified date of file '" + file.name + "' is " + new Date(file.lastModified));
}
function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='filename'>
<input type='button' id='btnShowModified' value='Show Modified' onclick='showFileModified();'>
</form>
</body>
</html>
The reason you couldn't get the time from the uploaded file on the server is that only the content of the file is transmitted in the request, not the client's filesystem metadata.
JavaScript does not have access to the local filesystem, so you can't get to this information without using Flash, Java or Active-x.
Perhaps you could use javascript to get the last modified time, then use that in some other javacript to sort on that. This time will be in GMT.
var xmlhttp = createXMLHTTPObject();
xmlhttp.open("HEAD", "http://myurl/interesting_image.jpg" ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert("Last modified: "+
var lastModTimeForInterestingImage = xmlhttp.getResponseHeader("Last-Modified"))
}
}
xmlhttp.send(null);
Currently I have some Python files which connect to an SQLite database for user inputs and then perform some calculations which set the output of the program. I'm new to Python web programming and I want to know: What is the best method to use Python on the web?
Example: I want to run my Python files when the user clicks a button on the web page. Is it possible?
I started with Django. But it needs some time for the learning. And I also saw something called CGI scripts. Which option should I use?
You are able to run a Python file using HTML using PHP.
Add a PHP file as index.php:
<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>
Passing the parameter to Python
Create a Python file as test.py:
import sys
input=sys.argv[1]
print(input)
Print the parameter passed by PHP.
It probably would depend on what you want to do. I personally use CGI and it might be simpler if your inputs from the web page are simple, and it takes less time to learn. Here are some resources for it:
cgi — Common Gateway Interface support
Python - CGI Programming
However, you may still have to do some configuring to allow it to run the program instead of displaying it.
Here's a tutorial on that: Apache Tutorial: Dynamic Content with CGI
If your web server is Apache you can use the
mod_python module in order to run your Python CGI scripts.
For nginx, you can use mod_wsgi.
Thanks to WebAssembly and the Pyodide project, it is now possible to run Python in the browser. Check out my tutorial on it.
const output = document.getElementById("output")
const code = document.getElementById("code")
function addToOutput(s) {
output.value += `>>>${code.value}\n${s}\n`
output.scrollTop = output.scrollHeight
code.value = ''
}
output.value = 'Initializing...\n'
// Init pyodide
languagePluginLoader.then(() => { output.value += 'Ready!\n' })
function evaluatePython() {
pyodide.runPythonAsync(code.value)
.then(output => addToOutput(output))
.catch((err) => { addToOutput(err) })
}
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Default Pyodide files URL ('packages.json', 'pyodide.asm.data', etc.)
window.languagePluginUrl = 'https://pyodide-cdn2.iodide.io/v0.15.0/full/';
</script>
<script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script>
</head>
<body>
Output:
</div>
<textarea id='output' style='width: 100%;' rows='10' disabled></textarea>
<textarea id='code' rows='3'>
import numpy as np
np.ones((10,))
</textarea>
<button id='run' onclick='evaluatePython()'>Run</button>
<p>You can execute any Python code. Just enter something
in the box above and click the button.
<strong>It can take some time</strong>.</p>
</body>
</html>
There's a new tool, PyScript, which might be helpful for that.
Official website
GitHub repository
You can't run Python code directly
You may use Python Inside HTML.
Or for inside PHP this:
http://www.skulpt.org/
You should try the Flask or Django frameworks. They are used to integrate Python and HTML.
There is a way to do it with Flask!
Installation
First you have to type pip install flask.
Setup
You said when a user clicks on a link you want it to execute a Python script
from flask import *
# Importing all the methods, classes, functions from Flask
app = Flask(__name__)
# This is the first page that comes when you
# type localhost:5000... it will have a tag
# that redirects to a page
#app.route("/")
def HomePage():
return "<a href='/runscript'>EXECUTE SCRIPT </a>"
# Once it redirects here (to localhost:5000/runscript),
# it will run the code before the return statement
#app.route("/runscript")
def ScriptPage():
# Type what you want to do when the user clicks on the link.
#
# Once it is done with doing that code... it will
# redirect back to the homepage
return redirect(url_for("HomePage"))
# Running it only if we are running it directly
# from the file... not by importing
if __name__ == "__main__":
app.run(debug=True)
You should use Py Code because it could run Any python script In html Like this:
<py-script>print("Python in Html!")<py-script>
Im not sure if it could run modules like Ursina engine ect But what i know is
That It allows you to type Python in Html. You can check out its offical Site for more info.
We can use Python code in HTML files. We have to use Python’s libraries within our browsers.
As we use Pyscript, we don’t need to worry about deployments. Everything happens in a web browser. We can share our HTML files with anyone containing fancy dashboards or any chars data. They can directly run it in a web browser without any complex setup.
Pyscript allows us to write python code with the help of 3 main components:
Py-env: It defines the python packages list which needs to run your
code.
Py-script: In this tag, the user will write their python code.
Py-repl: It will Create a REPL component. The REPL component
executes the code user enters and displays the result of the code in
the browser.
Let's start:
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
Our Hello world program will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>Python HTML app Hello World</title>
</head>
<body>
<py-script>
print("Hello World!")
</py-script>
</body>
</html>
This project is still in the alpha stage, so maybe we can see many more new things in the upcoming days. Let know more about how to use python in HTML file.
I have a Django view that is called from Angular with a $http.post
//LOADFILE ===================
this.loadfile = function (clickedItem) {
$http.post('/display/' , { "filename": clickedItem.fileName} )
.success(function(data) {
$scope.fileView.text = data;
$scope.fileView.title = clickedItem.title
}).error(function(data) {$scope.displayError=data});
};
If Django throws an error, data will be a full Django error page (full html page).
How do I display that error page (a complete html page) under Angular? (Some discussion of modals here : AngularJS, show popups - The most elegant way?, but nothing about a complete html page...)
I thought I could do this with a frame element and dom:
$window.frames['myErrorFrame'].document.innerHTML = $scope.displayError;
But that doesn't look very Angularish... And this almost does it, but I still have the problem of writing directly to the dom since the src is a string: insert an iframe into page dynamically in AngularJS
Is there a better way to display a full html page string in Angular?
Here is a possible solution. It works, but there are degrees of working, and this is a bit hacky -- the degree zero of working.
The error function (from Write elements into a child iframe using Javascript or jQuery):
update_error = function (message) {
var ifrm = document.getElementById('errorIFrame');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(message);
ifrm.document.close();
};
And the html:
<div ng-show="errorMessage != ''">
<button class="btn btn-info btn-xs" ng-click="errorMessage=''">Close</button><br />
<iframe width="100%" id="errorIFrame"> </iframe>
</div>
The error callback:
.error(function(data) {
update_error(data);
$scope.errorMessage="error"}
Note the switching of the errorMessage flag, which I seem to have to do because update_error is outside the controller (there must be a simple fix for that, but I have other fish to fry). This works, but I imagine it isn't orthodox. There is probably a better way with $sce (will fry that one later).
How do I put this python script:
a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
inside of a html file?
Something like this, if you want to create an html, not necessarily display it:
html_file = open('namehere.html','w')
a = ['f','d','s','a']
x = -1
scope = vars()
data = ''
for i in a: #TIP: use a generator
scope['x']+=1
data += a[x]
data += '\n'
html_file.write(data)
html_file.close()
There's now a solution to this, the solution is PyScript. This is a python framework that enables you to embed python scripts in HTML. Check out the sample code below.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script>
print("Hello World")
</py-script>
</body>
</html>
If your web server supports it, you could run it as a CGI script to output an HTML file - more information here: http://www.penzilla.net/tutorials/python/cgi/
You would need to modify your script to ouput valid HTML, but that tutorial should get you started.
Not possible. Python isn't like PHP; I can't just do this
<?php
And be good to go.
However, if your web server has a Python interpreter (most all do, these days), you can write CGI (common gateway interface) scripts to make Python code run on your webpage.
If you're trying to generate dynamic content (like change words in HTML), Javascript or PHP is better. Python is more suited to web applications.
if the script is in a server , you can run it using remote funcion call through JSON-RPC
you may refer the JSON-RPC documentation here
You can use {% %} tag in html and inside this you can write your python code.
Perhaps CGI is what you are looking for:
http://docs.python.org/library/cgi.html
http://www.penzilla.net/tutorials/python/cgi/
For example:
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<html><head></head><body><pre>"
a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
print "</pre></body></html>"
Surround it with a <body> and <head> tag and you're golden.
But seriously, I think what you are trying to do is print fdsa, which would would look like this:
<head>
<body>
fdsa
</body>
</head>
What you have there is not really a python script. You might need to correct that first, and then give a little more explanation what you are trying to do.
You can convert the thing into HTML or JavaScript. It would sort of be like this:
<script>
var a = ['f','d','s','a']
var x = -1
//other code
</script>
I am not showing the rest because I am not sure how to make a repeat loop.
You can't. If you want to run script in an HTML File, try another language like JavaScript or PHP. To include javascript, type this:
<script type="text/javascript">
// ...
</script>
Or in HTML5, you don't even have to type the type attribute:
<script>
// ...
</script>
To include PHP, type
<?php
// ...
?>