Some Additional Resources for CodeSkulptor
08/11/15 18:34 originally posted on Snippets of Code ... and Stuff

As we've seen before, Codeskulptor is a browser-based Python programming environment built by Scott Rixner that uses Skulpt to interpret/run python code in your browser.

Here are a few additional resources you can use:

super()

The super() function is not implemented in CodeSkulptor (actually in Skulpt). Here's a Super class disguised as the super function you can use instead. This uses python 2's syntax of super(Classname, self).method(...)

from user40_oKHcLUHi2y_6 import super

base64()

The following imports a base64 encoder that, thanks to one of CodeSkulptor's unique libraries (simplegui), works at almost the same speed as an equivalent JavaScript function.

from user40_fLJEVmzz56qKjnu import base64
print base64("Kevin van Zonneveld")

Reading Text Data from Dropbox or Google Drive

One of the custom CodeSkulptor modules is codeskulptor, which includes a file2url function. This function takes as a parameter a CodeSkulptor filename, and converts it into a readable/downloadable url. The following functions are designed to work similarly, but for Dropbox and Google Drive instead. They will return a url that can be used with CodeSkulptor's urllib2.urlopen function.

To read a shared text file from Dropbox
Call this function, passing it the dropbox url of the shared text file.
def dropboxfile2url(url):
url = url.replace("www.dropbox.","dl.dropboxusercontent.")
return url
For example,
import urllib2
my_file = urllib2.urlopen(dropboxfile2url(url))
print my_file.read()
Reading a shared text file from Google Drive
Similarly, call this function and pass it a Google Documents url (if the text file has been shared).
def googlefile2url(url):
#converts
#https://docs.google.com/document/d/randomID/edit
#to
#https://docs.google.com/document/export?format=txt&id=randomID
url = url.replace("/edit","")
baseurl = url.find("/",9)
part1 = url.find("/",baseurl+1)
part2 = url.find("/",part1+1)
url = url.replace(url[part1:part2+1],"/export?format=txt&id=")
return url
For example,
import urllib2
my_file = urllib2.urlopen(googlefile2url(url))
print my_file.read()

Data Permanence

The following store information to the cloud. The data will remain in the cloud permanently, or at least until the webservice clears the data.

You could, instead, set up your own server for data or database storage, but this is at your own risk and requires some knowledge and skills outside the scope of this post.
TinyWebDB
MIT App Inventor for Android provides an online public database service called TinyWebDB. By using the service provided by TinyWebDB, you can read/write a strings of data to the cloud.

App Inventor's TinyWebDB service has some limitations, but it provides instructions for running your own TinyWebDB service if you want privacy, or to not be bound by these limits.

According to the App Inventor for Android: TinyWebDB Service site:
NOTE: This service is being modified. It might go offline without notice
This service is only a demo. The database will store at most 250 entries; adding entries beyond that will cause the oldest entries to be deleted. Also, individual data values are limited to at most 500 characters.

Whether you wish to use MIT's public TinyWebDB database or run your own, the following code can be used to read and write data to the database:
from user40_z7IvquyR5AIkShD_0 import TinyWebDB

db = TinyWebDB(optional url for the TinyWebDB database)
a = db.read_cookie('test')
print a
db.write_cookie('test','this is cool')
print db.read_cookie('test')

db.write_cookie('test',a)
Yahoo's Sherpa Storage using YQL
By using the power of Yahoo Query Language (YQL), we can store information to Yahoo's Sherpa Storage. One of the tables available in YQL is the csv table which manages data in a comma-separated values file. This pseudo-database DB class can be imported and saves "cookies" to Yahoo's Sherpa storage, with the following restrictions:
from user37_sy2hPG6N72tRcaz_0 import DB

#sets up access to a YQL storage
#if you don't pass a select and an update URL,
# the default store will be used
db = DB(optional YQL_store_select, optional YQL_store_update)

# db.ReadUserCookies(app_name,user)
# read all cookies for a given app and user
# db.ReadCookie(app,user,cookie)
# read a cookie for a given app, user, and cookie name
# db.ReadAppUsers(app,cookie)
# read all users for a given app and cookie
# db.WriteCookie(app,user,cookie,value)
# write a cookie for a given app, user, and cookie name

Some CodeSkulptor Tricks
05/12/14 21:42 originally posted on Snippets of Code ... and Stuff

As we've seen before, Codeskulptor is a browser-based Python programming environment built by Scott Rixner of Rice University, and uses Skulpt to interpret/run python code.

Codeskulptor screenshot

Since Skulpt's python interpreter switches back and forth between Javascript objects and Python objects, some pieces of python code have slightly different effects when run within the Codeskulptor enviromnent than they would if run in Python, and these differences can be used to create useful effects.

Reading the Console

One such useful effect comes from using the open keyword. This keyword uses the ids of the page's DOM elements as filenames, but these "files" are currently read-only.

Everytime you use the print keyword, the string is shown in the console (on the right-hand column of the screen). This function will read the contents of the console and return it as a string.

def readConsole():
a = open("console")
return a.read()

Browser type detection

Another useful effect comes from using the file keyword. The open keyword uses file to find and return the contents of the DOM element whose id matches the "filename" being opened. However, if you call file directly, it returns an inmutable object of unknown type, which is actually a referrence to the Javascript window variable. Although this object is inmutable, dir is able to read its list of properties and methods.

This function is a moddified version of the browser-detection code used in Codeskulptor's simplegui module.

def browserPrefix():
w = dir(file("code"))
v = ['ms', 'moz', 'webkit', 'o'];
z = ''
for y in v:
if y+"RequestAnimationFrame" in w:
z += y
if z=='': z='unknown'
return z

Session cookies

This class uses file to set up a reference to the Javascript window variable. Then creates a simplegui Control class object with this reference to window. In combining these, the Control class is able to read and write to window.textContent. Since the window variable doesn't change when you re-run or reset the python code, window.textContent can be used to simulate session cookies.

import simplegui as sg
class SessionCookie:
__init__ = type('',[])
def __str__(self):
return ""
def setup():
a = file("code")
c = sg.Control(a)
def rsc(a):
try:
b = a.get_text()
return b
except:return ' '
c.set_text(rsc(c))
return c
__init__.setup = setup
del setup
def get_pos(c,name):
t = c.get_text()
r = t.find(" "+name+"=")
if (r==-1): return [-1,-1,-1,t]
else:
s = r + len(name) + 2
p = t.find(";",s)
return [r,s,p,t]
__init__.get_pos = get_pos
del get_pos
def get(self,name=None):
if name==None:
name = self
self = SessionCookie.__init__
a = self.get_pos(self.setup(),str(name))
if (a[0]==-1): return 'None'
else: return a[3][a[1]:a[2]]
def set(self,name,value=None):
if value==None:
name,value = self,name
self = SessionCookie.__init__
a = self.get_pos(self.setup(),str(name))
if (a[0]==-1): v = a[3]+" "+str(name)+"="+str(value)+";"
else:
v = a[3][0:a[0]]+a[3][a[2]+1:len(a[3])]+" "+str(name)+"="+str(value)+";"
self.setup().set_text(v)

Set an Unload Handler for a simplegui Frame

By default, when the user closes the simplegui popup window, the code is not notified of this event. This sometimes results in background audio that continues to play until the "reset" button is clicked. This function appends a set_unload_hander method to simplegui's Frame class. Any frames created after this automatically include this method. In this way, you can define a function to be called when the user closes the popup window.

def simplegui_frame_set_unload_handler(self,hand):
def unload_timer_check():
def gct():
try:
return self.get_canvas_textwidth("t",12)
except:
return 0
t = gct()
if t==0:
hand()
self.unload.stop()
self.unload = simplegui.create_timer(1000,unload_timer_check)
self.unload.start()
simplegui.Frame.set_unload_handler = simplegui_frame_set_unload_handler

Include these functions in you code

These functions can all be seen working here:http://www.codeskulptor.org/#user28_SWD5iUaoIAQvHpx_1.py.

To include these in your own projects, you can use import user28_SWD5iUaoIAQvHpx_1 in your code. Here's an example of the unload handler in use: http://www.codeskulptor.org/#user29_EdgayhvhdrqOaXu.py


How to Run Codeskulptor Python Programs on your own Page
08/12/13 19:10 originally posted on Snippets of Code ... and Stuff

Codeskulptor is a browser-based Python programming environment built by Scott Rixner of Rice University and is used in his An Introduction to Interactive Programming in Python class on Coursera.

Codeskulptor screenshot

In order to make the programming environment easy to use, Codeskulptor implements, among other things, a "simplegui" module which makes it easier to build interactive programs in the browser. The module is written in JavaScript and can therefore not be used in python projects outside of Codeskultor.

However, since CodeSkulptor is based on Skulpt and JavaScript, it should be possible to use these to run CodeSkulptor-specific interactive programs on your own website.

First, we visit Skulpt and copy the code under the heading "Getting Started". What we mostly need is all the code inside the <body> </body> tags.


<script type="text/javascript">
// output functions are configurable. This one just appends some text
// to a pre element.
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}

// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.canvas = "mycanvas";
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead});
eval(Sk.importMainWithBody("<stdin>",false,prog));
}
</script>

<h3>Try This</h3>
<form>
<textarea id="yourcode" cols="40" rows="10">import turtle

t = turtle.Turtle()
t.forward(100)

print "Hello World"
</textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<pre id="output" ></pre>
<!-- If you want turtle graphics include a canvas -->
<canvas id="mycanvas" ></mycanvas>

Second, we head over to Codeskulptor, and get a copy of the JavaScript include files there (to use in place of the ones used in Skulpt). As of this writing, the current list of included JavaScript files are


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="http://www.codeskulptor.org/js/jquery.flot.min.js"></script>
<script src="http://www.codeskulptor.org/js/jquery.flot.axislabels.min.js"></script>
<script src="http://www.codeskulptor.org/js/jquery.flot.orderbars.min.js"></script>
<script src="http://www.codeskulptor.org/js/numeric-1.2.6.min.js"></script>
<script src="http://www.codeskulptor.org/skulpt/skulpt.min.js"></script>
<script src="http://www.codeskulptor.org/skulpt/skulpt-stdlib.js"></script>
<script src="http://www.codeskulptor.org/js/codeskulptor-compressed.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

Ideally, you probably should copy those files to your own server (in case they change in the future), but you can, instead, just include those same JavaScript files on your own page, preferably in the header.

(There is one other JavaScript file include in Codeskulptor
<script src="http://www.codeskulptor.org/js/codemirror-compressed.js"></script>
but you don't need this one because it is part of CodeMirror's code to syntax-color the code.)

Then use the HTML+JavaScript code copied from Skulpt on your page.

Don't forget to put your python code as the contents of the textarea.

To see this in action, see here or at techni.ca here.


View Feed in Feedly Bookmarklet or Instructions
27/08/13 01:36 originally posted on Snippets of Code ... and Stuff

If, when clicking an RSS feed, you find yourself looking at a page full of code like this:

You can use the following bookmarklet to view the current feed in Feedly.

(Tested in Chrome version 29.0.1547.57)

View in Feedly

The code for the bookmarklet is:

javascript:window.open(String(document.location).replace(/(.*):\/\//,'http://cloud.feedly.com/#subscription/feed/$1://'));

If, instead, you use the RSS Subscription Extension (by Google) and would like to add Feedly to your list of available feed readers, you can

• click Manage...

• Then Add...

• give it a description and use the following for the URL
http://cloud.feedly.com/#subscription/feed/%s

• Dont' forget to [Save] and you're ready to go!

Happy reading! Meebo-smile.gif


Some of my shared IFTTT Recipes
26/08/13 02:59 originally posted on Snippets of Code ... and Stuff

IFTTT Recipe: Save FB Tagged Photos in Google DriveIFTTT Recipe: Text me the weather forcast for today every morning at 6AMIFTTT Recipe: Dictate a voice memo and email transcription and mp3 file to yourselfIFTTT Recipe: Save a timeline of facebook statuses to G CalIFTTT Recipe: Email 2 RSS 2 SMS ;^)

Powered by Feed Informer