Python Improperly Formatting AdSense code for GAE app?` - python

I have an AdSense ad embedding into the page http://mostpopnews.appspot.com/ (on the right most column / blank space) that's generated (along with the rest of the html by Python code used in GAE. It's been about 4 days since I created and embedded the ad script into the site, but the ad status has not changed from "New" to "Active". I am not sure why this is the case, as I have other blogs which convert to Active very quickly. Possibly because the site has not been indexed yet? My main hypothesis is that the Python code used to write the AdSense script is screwing something up with the HTML formatting that I can't see. Any ideas/
Python code for writing adsense script:
MAIN_PAGE_HTML = MAIN_PAGE_HTML + '''
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9089661734099673";
/* Top News */
google_ad_slot = "3468761149";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
'''
The source code of the webpage shows:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9089661734099673";
/* Top News */
google_ad_slot = "3468761149";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

Related

QWebEngineView.page().runJavaScript() does not run a JavaScript code correctly

I am making a Python program using PyQt5 GUI library.
I found out that using runJavaScript() method does not work for executing JavaScript code on my HTML document.
Here is my HTML document - a Mapbox GL JS component. It can also be found here: https://docs.mapbox.com/mapbox-gl-js/example/simple-map/ .
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display a map on a webpage</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.10.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.10.0/mapbox-gl.js"></script><script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoidmxhZGlra2lyIiwiYSI6ImNsNno2dnN3cjAxamYzbm4xeDhxa2xuY2oifQ.HhDTHZglHlDNte7XwGZ1Xg';
const map = new mapboxgl.Map({
container: 'map', // container ID
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [-74.5, 40], // starting position [lng, lat]
zoom: 9, // starting zoom
projection: 'globe' // display the map as a 3D globe
});
map.on('style.load', () => {
map.setFog({}); // Set the default atmosphere style
});
</script>
</body>
</html>
Here is a part of my Python code:
# Creating QWebEngineView widget called "mapView"
self.mapView = QtWebEngineWidgets.a
mapSizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
mapSizePolicy.setHeightForWidth(self.mapView.sizePolicy().hasHeightForWidth())
self.mapView.setSizePolicy(mapSizePolicy)
self.mapView.setObjectName("mapView")
self.detstartpointMapLayout.addWidget(self.mapView)
# Opening an HTML document and passing the components to QWebEngineView widget
with open('mapboxjs.html', 'r') as file:
mapHTML = file.read()
self.mapView.setHtml(mapHTML)
# Running a JavaScript code (with no success).
self.mapView.page().runJavaScript("const marker1 = new mapboxgl.Marker().setLngLat([12.554729, 55.70651]).addTo(map);")
Here is an error that my program returned:
js: Uncaught ReferenceError: mapboxgl is not defined .
I suppose this happens because runJavaScript() or QWebEngineView do not notice libraries that I have imported before in HEAD section of the HTML document using tag. How to I bypass that?
The same JavaScript command works with no errors when I open the HTML code in Firefox and send JS code into the console.
My suggestion was right - it happened because the JS function in page.runJavaScript() was executed before the .js script in HEAD section of the HTML file has completed it's execution.
So, to solve the issue I delayed page().runJavascript() execution until the HTML file finishes loading completely (including .js file in the HEAD section) by replacing
self.widgetname.page().runJavaScript("someJavaScriptFunction")
with
self.widgetname.page().loadFinished.connect(lambda: self.widgetname.page().runJavaScript("someJavaScriptFunction"))
Don't forget to include lambda: before the self.widgetname.page().runJavaScript() .

How to allow speech recogonition api in QWebEngineView

I have a small code
<!doctype html>
<head>
<title>JavaScript Speech to Text</title>
</head>
<body>
<h2>JavaScript Speech to Text</h2>
<p>Click on the below button and speak something...</p>
<p><button type="button" onclick="runSpeechRecognition()">Speech to Text</button> <span id="action"></span></p>
<div id="output" class="hide"></div>
<script>
/* JS comes here */
function runSpeechRecognition() {
// get output div reference
var output = document.getElementById("output");
// get action element reference
var action = document.getElementById("action");
// new speech recognition object
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var recognition = new SpeechRecognition();
// This runs when the speech recognition service starts
recognition.onstart = function() {
action.innerHTML = "<small>listening, please speak...</small>";
};
recognition.onspeechend = function() {
action.innerHTML = "<small>stopped listening, hope you are done...</small>";
recognition.stop();
}
// This runs when the speech recognition service returns result
recognition.onresult = function(event) {
var transcript = event.results[0][0].transcript;
var confidence = event.results[0][0].confidence;
output.innerHTML = "<b>Text:</b> " + transcript + "<br/> <b>Confidence:</b> " + confidence*100+"%";
output.classList.remove("hide");
};
// start recognition
recognition.start();
}
</script>
</body>
It does not work on PyQtWebEngine
How to make it work.
I searched for it and found that only chromium based browser supports speech recogonition.
PyQtWebEngine is Chromium Based then How to make it work
Although this feature is available in chromium but it has been disabled by Qt as indicated in this report. Maybe in the following versions of Qt6 it will be enabled.

Embedding Python Game Into HTML Using Skulpt

I have written a game in Python using the PyGame library that I am trying to embed into an HTML page to allow me to play in a web browser.
I am attempting to do this using the JavaScript library Skulpt. I have attached a test script below that successfully outputs the print statement below.
skulpt.html
<html>
<head>
<script src="assets/skulpt/skulpt.js" type="text/javascript"></script>
</head>
<body>
<textarea id="pythonCode">
print "I am python."
</textarea><br />
<pre id="output"></pre>
<script type="text/javascript">
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
var code = document.getElementById("pythonCode").value;
Sk.configure({output:outf});
eval(Sk.importMainWithBody("<stdin>",false,code));
</script>
</body>
</html>
Output of skulpt.html:
The issue that I am having is that when I use my game code instead of the simple print statement shown above it produces the error seen below;
I have included all relevant images to my web servers' directory at the correct path. I am unsure of why this error is being produced. Any help would be much appreciated, thanks!
Also, here is the attached Python game code (and a live demo of the error):
http://nicolasward.com/portfolio/skulpt.html
You have a lot of indentation on line 1 -> remember, in python, indentation always matters. Take away all those spaces/tabs on the first line and it should run.

Display multiple mpld3 exports on a single HTML page

I've found the mpld3 package to be brilliant for exporting a matplolib plot to HTML and displaying this via a flask app.
Each export comes with a lot of JS which seems unnecessary duplication if you want to display multiple plots within a single page. However I'm not well enough versed in JS to extract the relevant components and then loop through them. The .fig_to_dict method gives the necessary JSON to display each chart but then I'm left wondering what JS/ template work is needed to display each chart in turn.
I considered just stacking each plot into a single big figure but I'd like to layout the charts in separate DIVs and so this isn't the right solution.
I think I can see what the JS is doing to display them but I don't have enough knowledge to modify the functions to suit the purpose.
I haven't included code as I'm expecting this only to be relevant to someone with mpld3 experience but can supply some sample code if needed.
Sample HTML output for mpld3.fig_to_html(fig, template_type="simple"):
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.1.js"></script>
<style>
</style>
<div id="fig136845463888164451663379"></div>
<script type="text/javascript">
var spec136845463888164451663379 = { <snip JSON code> };
var fig136845463888164451663379 = mpld3.draw_figure("fig136845463888164451663379", spec136845463888164451663379);
</script>
I'd thought it would be as simple as linking the two core scripts from the template header and then creating a new script for each JSON export. But that hasn't worked for me.
You're half-way there with your answer. I think what you want to do is something like this, which will embed three figures on the page:
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.1.js"></script>
<style>
</style>
<div id="fig01"></div>
<div id="fig02"></div>
<div id="fig03"></div>
<script type="text/javascript">
var json01 = { <snip JSON code> };
var json02 = { <snip JSON code> };
var json03 = { <snip JSON code> };
mpld3.draw_figure("fig01", json01);
mpld3.draw_figure("fig02", json02);
mpld3.draw_figure("fig03", json03);
</script>
The json code for each figure can be created in Python by running
import json
# ... create matplotlib figure
json01 = json.dumps(mpld3.fig_to_dict(fig))
Embed this string at the appropriate place in the HTML document you're creating, and you should be good to go. I hope that helps!
Note that since jakevdp's answer was posted mpld3 has had a new release. As of today (September 2014) the mpld3 include has to be:
<script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.2.js"></script>

How to pass data from Google App Engine(Python) to Flex 4 application

I am using python and webapp framework in app engine for backend and flex 4 for front end.
I would like to pass a string form backend to front end, so i write the following code in the main.py:
class MainPage(webapp.RequestHandler):
def get(self):
userVO = "test"
template_values = {
'url': self.request.uri,
'userVO': userVO,
}
self.response.out.write(template.render("templates/index.html", template_values))
And in the flex 4, I have the following code:
var user:String = FlexGlobals.topLevelApplication.parameters['userVO'];
However, I receive null value.
Please advice how to correct it. Thanks.
Edit: 25 Feb.
Thanks for the people who answer my question. For my question, I am try to figure out how the python app engine pass data to flex app when it render the html file that include the swf file. Maybe, there is something I can set in the main.py, swfobject.js or the index.html to do my task.
I know how to use Pyamf as a gateway to serve the flex app, I am thinking how to make the app more simple.
Thanks.
Edit: 28 Feb.
Robert, the index.html is the standard file created by flash builder 4. Wish you can give me some hints how to modify it. The following is the file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<!--
Smart developers always View Source.
This application was built using Adobe Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops via Adobe AIR.
Learn more about Flex at http://flex.org
// -->
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
html, body { height:100%; }
body { margin:0; padding:0; overflow:hidden; text-align:center; }
#flashContent { display:none; }
<script type="text/javascript" src="/js/swfobject.js"></script>
<script type="text/javascript">
<!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
var swfVersionStr = "10.0.0";
<!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
var xiSwfUrlStr = "/swfs/playerProductInstall.swf";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
var attributes = {};
attributes.id = "index";
attributes.name = "index";
attributes.align = "middle";
swfobject.embedSWF(
"/swfs/index.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
To view this page ensure that Adobe Flash Player version
10.0.0 or greater is installed.
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="index">
<param name="movie" value="index.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<!--[if !IE]>
<object type="application/x-shockwave-flash" data="index.swf" width="100%" height="100%">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<![endif]-->
<!--[if gte IE 6]>
<p>
Either scripts and active content are not permitted to run or Adobe Flash Player version
10.0.0 or greater is not installed.
</p>
<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="https://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
</a>
<!--[if !IE]>
</object>
<![endif]-->
</object>
</noscript>
Thanks, Robert.
Edit: 7 Mar.
Robert,
Refer to http://help.adobe.com/en_US/Flex/4.0/html/WS2db454920e96a9e51e63e3d11c0bf626ae-7feb.html
Before I post the question here, I tried the following code:
In the index.html,
<%
String user = (String) request.getParameter("userVO");
%>
and also
flashvars.userVO = "<%= user %>";
The result, I get:
< user
Do you know why I can't get the correct data. Thanks.
The best way to talk from Flex to GAE is using AMF. Here is how:
app.yaml
application: flexandthecloud
version: 3
runtime: python
api_version: 1
handlers:
- url: /services/.*
script: main.py
main.py
#!/usr/bin/env python
import wsgiref.handlers
from pyamf.remoting.gateway.wsgi import WSGIGateway
def sayHello(name):
return "howdy " + name
services = {
'services.sayHello': sayHello
}
def main():
application = WSGIGateway(services)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Flex 3 code (can be easily modified for Flex 4):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:RemoteObject id="ro" destination="services" endpoint="http://flexandthecloud.appspot.com/services/">
<mx:result>
l.text = event.result as String;
</mx:result>
</mx:RemoteObject>
<mx:TextInput id="ti"/>
<mx:Label id="l"/>
<mx:Button label="say hello" click="ro.sayHello(ti.text)"/>
</mx:Application>
Based on your comment to James Ward's response, I wonder if you can accomplish what you need with a FlashVars param element?
http://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_3.html
You will probably just need to adjust the index.html template to build the FlashVars param element.
Edit: 6 Mar
You might try looking at:
http://polygeek.com/801_flex_reading-flashvars-in-flex
You need to be sure you wait until the app has been loaded to access the flashVars.
Edit: 7 Mar
Correct, in those examples they hard code the value. You need to edit your template so the value is set to the value of the template parameter.
So, in index.html:
flashvars.userVO = "{{ userVO }}"
What's in your index.html?
You can pass the values to index.html, set a javascript function like:
function passvalue {
PassParameter("userVO", "{{userVO}}");
}
Then set a function in Flex:
public function gethtmlparam(name:String, val:String):void {
switch (name) {
case "userVO": userVO= val; break;}
}
and call back these two function in :
ExternalInterface.addCallback("PassParameter", gethtmlparam);
Hope it can help.

Categories