I'm developing a web application in linux environnement to display image of data array.
So i would like to save images from python plot to jpeg files to be able to display them in a browser. Python code works correctly when executed from the console. But if called with a javascript request it hangs due to plt use, even with pltioff(). done message is send if i remove all plt code.
python :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import os
import json
curr = os.getcwd()
plt.ioff()
fig, ax = plt.subplots( 1 )
ax.plot([1, 2, 3])
plt.show()
fig.savefig(curr+"/"+'test.jpeg',dpi=224,quality=50)
messJ = json.dumps( "done" )
print('Content-type: text/html')
print("\n")
print "%s" %messJ
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>my page</title>
</head>
<body >
<input type="button" id="plotsrv" value="plotsrv" />
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="pythonplot.js"></script>
javascript :
document.getElementById('plotsrv').addEventListener('click', trait_Vdatasrv, false);
function trait_Vdatasrv (e) {
var url = 'pyplot.py';
console.log("url:"+url);
$.post(url,{ file:'ncfile' }, function(data){
$('#data').html(data);
console.log("data"+data);
var jsdec=JSON.parse(data);
console.log(jsdec); }
); }
Regards
I finally found ,
it is needed to add matplotlib.use('Agg')
to avoid display output
Related
I am calling a SOAP service in my Javascript code, and the response of this service is correct but strings returned does not show letters with accents. So, I have a problem with encoding charset and I am trying the following actions:
1) I ensure that the HTTP response returning string data has the correct charset defined. So, I have checked with https://validator.w3.org/i18n-checker/ that the encoding charset of the URI that I am calling is "utf-8".
2) I have defined charset in the head section of html:
<meta charset='utf-8' content-type="text/xml;charset=UTF-8"/>
3) Also, I call this service with a function in module.js, I have also defined
<script src="node_modules/my_module.js" charset="utf-8"></script>
All three with the same wrong result.
I added an image with the some examples:
image with result strings, where in green square have to say 'Sant Martí de Tous', in red 'Moianès', in blue 'Santa Bàrbara', 'Montsià', in orange 'Torroella de Montgrí', etc
This is a minimum sample code to call SOAP service with tinysoap library:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' content-type="text/xml; charset=utf-8"/>
<title>Test Charset Encoding</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="node_modules/tinysoap/tinysoap-browser-min.js"></script>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
var tinySoap=this.tinysoap;
require(["esri/Map"], function(Map) {
var inputCtrl = document.getElementById("inputString"); // gironès
var outputCtrl = document.getElementById("outputString");
inputCtrl.onchange = function() {
var userTxtValue = inputCtrl.value;
var args = {nom: userTxtValue};
//console.log("[INPUT] : ",args);
//outputCtrl.innerHTML = "<br><b>Input ... </b>" + userTxtValue +"<br>";
tinySoap.createClient(url, function(err, client){
client.localitzaToponim(args, function(err, result) {
var data = result['item'];
//console.log("[OUTPUT] : ",data);
//outputCtrl.innerHTML += "<b>Output ... </b>";
//data.forEach(element => {
// outputCtrl.innerHTML += "<br> "+ element.Nom;
//});
});
});
}
});
</script>
</head>
<body>
Look for place or address ...
<input id="inputString" size="50" value=""><br>
<span id="outputString"></span>
</body>
</html>
This is the result of this process for 'gironès' as input string
There is the error: "Refused to set unsafe header", but I can not see where to set header parameters to connection.
I am still working in that problem: I have checked that strings are encoded as UTF16 with this library: https://github.com/polygonplanet/encoding.js/
using Encoding.detect(string), but Encoding.convert(string,'utf8','utf16') does not work for me, neither Encoding.convert(string,'latin1','utf16'), etc
What is the right way to define the encoding charset? Thank you
I am using flask to build online app. I am grabbing user input using d3.js then send it off to app.py which will use this input to make an api call and grab appropriate data then it will return jsonfied data back to javascript for rendering plot in correct html tag however it keeps on giving me error: Error: DOM element provided is null or undefined
app.py:
import os
from flask import Flask, render_template, jsonify, request, redirect, url_for
from alpha_vantage.timeseries import TimeSeries
import plotly
# import plotly.plotly as py
# import plotly.graph_objs as go
app = Flask(__name__)
api_key = "ssdqwjhwq"
# This will run upon entrance
#app.route("/")
def home():
return render_template("index.html")
#app.route("/stockchart/<label>")
def stock_data(label):
ts = TimeSeries(key=api_key, output_format='pandas')
df, meta_deta = ts.get_daily(label, outputsize="full")
df.columns = ["open", "high", "low", "close", "volume"]
data = [{"dates":list(df.index.values)},
{"close": list(df.close)}]
return jsonify(data)
if __name__ == "__main__":
app.run()
my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Stock Screener</title>
<!-- Importing all cdn -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="text-center">
<h2>Stock Screener</h2>
<h5>Interactive chart with predictions using machine learning</h5>
</div>
<div>
<!-- Input for stock label -->
<form>
<label for="stockInput">Enter stock label</label>
<!-- use js to store input into a variable. -->
<input type="text" id="stockInput" name="stock_label" placeholder="Label">
<!-- submit button-->
<input type="submit" value="submit" id="stocklabelsubmit">
</form>
</div>
<div class="chart">
</div>
</body>
<script src="../static/js/index.js"></script>
</html>
And my javascript
// give reference to submit button
// Upon click, submitted function will run
d3.select("#stocklabelsubmit").on("click", submitted);
function submitted(){
d3.event.preventDefault();
// grab label inputted.
var inputted_label = d3.select("#stockInput").node().value;
// refresh input box
d3.select("#stockInput").node().value = "";
// pass inputted_label to plot function
Plot(inputted_label);
};
function Plot(input){
var url = `/stockchart/${input}`
// when this function is called call /stock_data function!!
// data is what is returned from python
d3.json(url).then(function(data){
console.log(data);
console.log(data[0]);
console.log(data[0].dates);
var trace = {
x:data[0].dates,
y:data[1].close,
type: "scatter"
};
var layout {
title:"Stock chart",
xaxis:{
title:"dates"
},
yaxis:{
title:"closing price"
}
};
var data = [trace];
// var loc_plot = document.getElementById("chart");
Plotly.newPlot("chart", data, layout);
});
};
Error tells me that there is an error in js line 33 = Plotly.newPlot("chart", data,layout); I am not sure how I can fix this everything seems to work fine until plotting as it console logs properly. Any help? Thanks!
According to the documentation, the graphDiv argument of Plotly.newPlot() refers to either a DOM node or string ID of a DOM node.
In your code above, it looks like you are providing neither. You are providing the class of a DOM node, but not an actual DOM node or ID of a DOM node. This probably explains the error you're getting regarding the null or undefined DOM node.
Try changing <div class="chart"> to <div class="chart" id="chart"> (or some other ID), or get the node using Element.querySelector() and pass that in for the DOM node instead and see if that works.
I am still a beginner in JavaScript. I have written a code with two nested for-loops. It achieves the result but that is too large to be copied in Android. It copies part but not all data.
How can I export my data as .csv file or .txt file i.e. a button in HTML file, I click on it then the data is exported as .csv?
My HTML code:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button onclick="convert()"> Convert </button>
</body>
</html>
My JavaScript code:
function convert(){
var lon,lat;
for(lat = 52 + (2226/3600) ; lat <= 52 + (2425/3600) ; lat=lat+(1/3600))
{
for(lon = 9 + (3539/3600) ; lon<= 10 + (215/3600) ; lon=lon+(1/3600))
{ document.write("W,"+lat+","+lon+"<br>") }
}
};
My data are browsed fully and without problem in webpage HTML as followed after clicking convert button:
W,52.61833333333333,9.983055555555556
W,52.61833333333333,9.983333333333333
W,52.61833333333333,9.98361111111111
W,52.61833333333333,9.983888888888886
W,52.61833333333333,9.984166666666663 ..........
W,52.61833333333333,9.98444444444444
Hopefully I can export all these data so as .csv or .txt file.
I want to read the status of my digital pins of arduino and want to display it
in web page. For web programming i am using Flask. I tried this code but its not working. from arduino side I am reading the values of 6 digital pins in the form of 1 and 0. How i can do this? Any help would be appreciated.
<!doctype html>
<html>
<head>
</head>
<body>
<h1 style="font-size:30px;font-family:verdana;"><b>STATUS READ </h1><br><br>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="#status1"></p>
<p id="#status2"></p>
<p id="#status3"></p>
<p id="#status4"></p>
<p id="#status5"></p>
<p id="#status6"></p>
<script type=text/javascript>
function updatevalues() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/a",
function(data) {
$("#status1").text(data.m+" %")
$("#status2").text(data.n+" %")
$("#status3").text(data.o+" %")
$("#status4").text(data.p+" %")
$("#status5").text(data.q+" %")
$("#status6").text(data.r+" %")
});
}
</script>
</body>
</html>
Python code:
from flask import Flask, render_template,request,redirect, url_for,jsonify,flash
import flask
from shelljob import proc
import math
import eventlet
eventlet.monkey_patch()
from flask import Response
import serial
import time
from datetime import datetime
import json
import random
from flask.ext.bootstrap import Bootstrap
from flask_bootstrap import WebCDN
app = flask.Flask(__name__)
app.secret_key = 'some_secret'
bootstrap = Bootstrap(app)
app.extensions['bootstrap']['cdns']['jquery'] = WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/')
arduino= serial.Serial( '/dev/ttyACM0' , 9600) #creating object
#app.route('/')
def home():
return render_template('status.html')
#app.route('/a',methods=['GET'])
def a():
mydata=arduino.readline().split(',')
return jsonify(m=float(mydata[0]),n=float(mydata[1]),o=float(mydata[2]),p=float(mydata[3]),q=float(mydata[4]),r=float(mydata[5]))
if __name__ == "__main__":
app.run()
It seems like you're not calling updatevalues in Javascript. You should try with something like this:
setInterval(updatevalues, 1000); //So it runs the function every 1000ms (1 second)
I get an error when i would like to render html file which contains a script link on js file.
But when i load page i get this error :
Started GET "/views/script.js" .... Returning 404
my folder is like this
|--todolist
|--main.go
|--views/
|--index.html
|--script.js
main.go
package main
import (
"github.com/zenazn/goji"
"html/template"
"net/http"
)
func renderHTMLPage(w http.ResponseWriter, path string) {
t, err := template.ParseFiles(path)
if err != nil {
panic(err)
}
t.Execute(w, nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
renderHTMLPage(w, "./views/index.html")
}
func main() {
goji.Get("/", Index)
goji.Serve()
}
views/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Le titre du document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="script.js"></script>
<h1>To-Do List </h1>
<ul id="todolist">
<li> Hello <button>Delete</button></li>
<li> Wesh <button>Delete</button></li>
</ul>
<input type="text" id="new-text" /><button id="add">Add</button>
</body>
</html>
views/script.js
function addListItem() {
var text = $('#new-text').val()
if (text != "") {
$('#todolist').append('<li>'+text+'<button id="dede" name=\"' + i + '\">Delete</button></li>')
}
$('#new-text').val("")
}
function deleteItem() {
$(this).parent().remove()
}
$(function() {
$('#add').on('click', addListItem);
$("#todolist").on("click", "#dede", deleteItem)
});
How can I do to make it properly load the js file ?
And what is the best way to create an app who use only jquery/javascript with a golang api on architecture ?
Thank you
You need to either:
Serve from the directory containing /views - e.g. goji.Get("/views/*", http.FileServer(http.Dir("/Users/matt/Desktop/views/")))`
Use http.StripPrefix (recommended)
The below allows you to decouple the path from the directory name:
func main() {
goji.Get("/views/*", http.StripPrefix("/views", http.FileServer(http.Dir("/Users/matt/Desktop/views/"))))
goji.Get("/", Index)
goji.Serve()
}
I'd recommend against serving from the 'root' - /*. Better to serve from a dedicated assets path as it makes it easier when looking at caching, interacting with CDNs, etc.
In this particular case code should look like
goji.Get("/", Index)
goji.Get("/*", http.FileServer(http.Dir("./views")))
goji.Serve()
But I must say keeping template and static files in same directory is bad idea as well as serving static files from root.