Skip to content

Commit

Permalink
add one liner solution (issue #69)
Browse files Browse the repository at this point in the history
  • Loading branch information
bearney74 committed Feb 3, 2015
1 parent ca1139f commit 541d373
Show file tree
Hide file tree
Showing 2 changed files with 378 additions and 0 deletions.
330 changes: 330 additions & 0 deletions site/one-liner.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,330 @@
<!doctype html>
<html>
<head>
<meta name="description" content="Brython">
<meta name="keywords" content="Python,Brython">
<meta name="author" content="Pierre Quentel">
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">

<noscript>Please enable Javascript to view this page correctly.</noscript>
<script type="text/javascript" src="/src/one-liner.js"
data-brython-options='{"debug":1,"cache":"none"}'></script>

<script type="text/python3">
"""Code for the header menu"""
from browser import document as doc
from browser import html
import header

qs_lang,language = header.show()

doc["content"].html = doc["content_%s" %language].html

if qs_lang:
doc["c_%s" %qs_lang].href += "?lang=%s" %qs_lang

def ch_lang(ev):
sel = ev.target
new_lang = sel.options[sel.selectedIndex].value
doc.location.href = 'index.html?lang=%s' %new_lang

for elt in doc[html.SELECT]:
if elt.id.startswith('change_lang_'):
doc[elt.id].bind('change',ch_lang)
</script>

<script type="text/python3">
"""Code for the clock"""

import time
import math
import datetime

from browser import document as doc
import browser.timer

sin,cos = math.sin,math.cos
width,height = 250,250 # canvas dimensions
ray = 100 # clock ray

def needle(angle,r1,r2,color="#000000"):
# draw a needle at specified angle in specified color
# r1 and r2 are percentages of clock ray
x1 = width/2-ray*cos(angle)*r1
y1 = height/2-ray*sin(angle)*r1
x2 = width/2+ray*cos(angle)*r2
y2 = height/2+ray*sin(angle)*r2
ctx.beginPath()
ctx.strokeStyle = color
ctx.moveTo(x1,y1)
ctx.lineTo(x2,y2)
ctx.stroke()

def set_clock():
# erase clock
ctx.beginPath()
ctx.fillStyle = "#FFF"
ctx.arc(width/2,height/2,ray*0.89,0,2*math.pi)
ctx.fill()

# redraw hours
show_hours()

# print day
now = datetime.datetime.now()
day = now.day
ctx.font = "bold 14px Arial"
ctx.textAlign = "center"
ctx.textBaseline = "middle"
ctx.fillStyle="#FFF"
ctx.fillText(day,width*0.7,height*0.5)

# draw needles for hour, minute, seconds
ctx.lineWidth = 3
hour = now.hour%12 + now.minute/60
angle = hour*2*math.pi/12 - math.pi/2
needle(angle,0.05,0.5)
minute = now.minute
angle = minute*2*math.pi/60 - math.pi/2
needle(angle,0.05,0.85)
ctx.lineWidth = 1
second = now.second+now.microsecond/1000000
angle = second*2*math.pi/60 - math.pi/2
needle(angle,0.05,0.85,"#FF0000") # in red

def show_hours():
ctx.beginPath()
ctx.arc(width/2,height/2,ray*0.05,0,2*math.pi)
ctx.fillStyle = "#000"
ctx.fill()
for i in range(1,13):
angle = i*math.pi/6-math.pi/2
x3 = width/2+ray*cos(angle)*0.75
y3 = height/2+ray*sin(angle)*0.75
ctx.font = "20px Arial"
ctx.textAlign = "center"
ctx.textBaseline = "middle"
ctx.fillText(i,x3,y3)
# cell for day
ctx.fillStyle = "#000"
ctx.fillRect(width*0.65,height*0.47,width*0.1,height*0.06)

canvas = doc["clock"]
# draw clock border
if hasattr(canvas,'getContext'):
ctx = canvas.getContext("2d")
ctx.beginPath()
ctx.lineWidth = 10
ctx.arc(width/2,height/2,ray,0,2*math.pi)
ctx.stroke()

for i in range(60):
ctx.lineWidth = 1
if i%5 == 0:
ctx.lineWidth = 3
angle = i*2*math.pi/60 - math.pi/3
x1 = width/2+ray*cos(angle)
y1 = height/2+ray*sin(angle)
x2 = width/2+ray*cos(angle)*0.9
y2 = height/2+ray*sin(angle)*0.9
ctx.beginPath()
ctx.moveTo(x1,y1)
ctx.lineTo(x2,y2)
ctx.stroke()
browser.timer.set_interval(set_clock,100)
show_hours()
else:
doc['navig_zone'].html = "On Internet Explorer 9 or more, use a Standard rendering engine"
</script>


<title>Brython</title>
<link rel="stylesheet" href="doc/doc_brython.css">
</head>
<!--
options:
debug: can equal 0,1,2. more verbose as number increases
cache: 'none', 'version', 'browser'.
'none' - no caching allowed. a new random number is appended to end of each request
'version' - caching allowed for each new brython version
'browser' - nothing is appended to request. A clients browser is responsible for caching actions.
pythonpath: a list of additional urls/paths to search for modules
-->
<body>

<table id="banner" cellpadding=0 cellspacing=0>
<tr id="banner_row">
</tr>
</table>

<div id="content"></div>

<div id="content_en" style="height:1px;visibility:hidden">

<table style="width:85%;margin-left:10%">
<tr>
<td>
<H1 style="font-size:300%;">Brython</H1>
<H2>A Python 3 implementation for client-side web programming</H2>
</td>
<td valign="top">
<select class="language" id="change_lang_en">
<option value="en" selected>English
<option value="es">Espa&ntilde;ol
<option value="fr">Fran&ccedil;ais
</select>
</td>
</tr>
</table>

<table style="width:85%;margin-left:10%">
<tr>
<td style="width:65%;font-size:16px;">
Without a doubt, you've seen a clock like this in demos of HTML5
<p>
However, right click and view the source of this page...
<p>It is not Javascript code! Instead, you will find Python code in a script of type "text/python"
<p>Brython is designed to replace Javascript as the scripting language for the Web. As such, it is a Python 3 implementation (you can take it for a test drive through a web <a href="console.html" id="c_en">console</a>), adapted to the HTML5 environment, that is to say with an interface to the DOM objects and events
<p>The <a href="gallery/gallery_en.html">gallery</a> highlights a few of the possibilities, from creating simple document elements to drag and drop and 3D navigation. A <a href="https://github.com/brython-dev/brython/wiki/Brython%20in%20the%20wild">wiki</a> lists some applications using Brython.
<p><a href="http://pyschool.net">pyschool.net</a> provides a web-based environment for teachers in Python classes
<p>You can also take a look at <a href="https://github.com/brython-dev/brython/wiki/Brython-videos-and-talks">presentations</a> made in various conferences</td>

<td style="padding-left:5%;">
<canvas width="250" height="250" id="clock">
<i>sorry, Brython can't make the demo work on your browser ; <br>check if Javascript is turned on
<br><div id="navig_zone"></div></i>
</canvas>
</td>

</tr>

</table>

</div>

<div id="content_fr" style="height:1px;visibility:hidden">
<table style="width:80%;margin-left:10%">
<tr>
<td>
<H1 style="font-size:300%;">Brython</H1>
<H2>Une implémentation de Python 3 pour la programmation web côté client</H2>
</td>
<td valign="top">
<select class="language" id="change_lang_fr">
<option value="en">English
<option value="es">Espa&ntilde;ol
<option value="fr" selected>Fran&ccedil;ais
</select>
</td>
</tr>
</table>

<table style="width:80%;margin-left:10%">
<tr>
<td style="width:60%;font-size:16px;">
Des horloges comme celle-ci, vous en avez sans doute déjà vu dans des démos d'HTML5
<p>
Maintenant, regardez le code source de cette page...
<p>Vous ne verrez pas une ligne de Javascript, mais à la place, du code Python dans un script de type "text/python"
<p>Brython a pour objectif de remplacer Javascript comme langage de script des pages Web. Il s'agit donc d'une implémentation de Python 3 (que vous pouvez tester sur la <a href="console.html" id="c_fr">console</a>), adaptée à l'environnement HTML5, c'est-à-dire dotée d'une interface avec les objets et les événements DOM
<p>Une <a href="gallery/gallery_fr.html">galerie</a> présente quelques démos de ce qu'il est possible de faire, depuis la création d'éléments simples jusqu'au glisser-déposer ou la navigation 3D. Un <a href="https://github.com/brython-dev/brython/wiki/Brython%20in%20the%20wild">wiki</a> répertorie quelques applications utilisant Brython
<p><a href="http://pyschool.net">pyschool.net</a> fournit un environnement web pour l'enseignement de Python
<p>Vous pouvez également consulter <a href="https://github.com/brython-dev/brython/wiki/Brython-videos-and-talks">plusieurs présentations de Brython</a> dans diverses conférences
</td>

<td style="padding-left:5%;">
<canvas width="250" height="250" id="clock">
<i>désolé, Brython n'arrive pas à faire fonctionner la démo sur votre navigateur ;<br>vérifiez que Javascript est activé
<br><div id="navig_zone"></div></i>
</canvas>
</td>
</tr>
</table>

</div>

<div id="content_es" style="height:1px;visibility:hidden">
<table style="width:80%;margin-left:10%;">
<tr>
<td>
<H1 style="font-size:300%;">Brython</H1>
<H2>Una implementación de Python para la programación web del lado del cliente</H2>
</td>
<td valign="top">
<select class="language" id="change_lang_en">
<option value="en">English
<option value="es" selected>Espa&ntilde;ol
<option value="fr">Fran&ccedil;ais
</select>
</td>
</tr>
</table>

<table style="width:80%;margin-left:10%">
<tr>
<td style="width:60%;font-size:16px;">
Muy cierto que has visto relojes de este tipo en demos de HTML5
<p>
Pero, mira el código fuente de esta página...
<p>No hay lineas de Javascript, es puro código Python dentro de un script de tipo "text/python"
<p>Brython es diseñado para remplazar a JavaScript como lenguaje de scripting para páginas web. Por lo tanto, es una implementación de Python 3 (que se puede probar en la <a href="console.html" id="c_es">consola</a>), adaptada a un entorno HTML5, es decir, con una interfaz con los objetos y eventos DOM
<p>Una <a href="gallery/gallery_es.html">galería</a> presenta algunas maquetas de lo que se puede hacer, de la creación de elementos, a ejemplos de arrastrar y soltar a navegación 3D
<p>Una <a href="https://github.com/brython-dev/brython/wiki/Brython%20in%20the%20wild">wiki</a> que muestra un listado de algunas aplicaciones que funcionan usando Brython
<p>Además, le puedes echar un vistazo a<a href="https://github.com/brython-dev/brython/wiki/Brython-videos-and-talks"> estas presentaciones</a> mostradas en varias conferencias</td>
</td>
<td style="padding-left:5%;">
<canvas width="250" height="250" id="clock">
<i>El navegador no soporta HTML5 canvas<br>o el Javascript es apagado
<br><div id="navig_zone"></div></i>
</canvas>
</td>
</table>

</div>

<div id="content_pt" style="height:1px;visibility:hidden">

<table style="width:80%;margin-left:10%">
<tr>
<td>
<H1 style="font-size:300%;">Brython</H1>
<H2>Uma implementação de Python 3 para a programação web do lado do cliente</H2>
</td>
<td valign="top">
<select class="language" id="change_lang_pt">
<option value="en">English
<option value="es">Espa&ntilde;ol
<option value="fr">Fran&ccedil;ais
<option value="pt" selected>Portugu&ecirc;s
</select>
</td>
</tr>
</table>

<table style="width:80%;margin-left:10%">
<tr>
<td style="width:60%;font-size:16px;">
Sem dúvida você já viu um relógio como este em demonstrações de HTML5
<p>
Entretanto, clique com o botão direito e veja o código fonte desta págna...
<p>Não é código em Javascript! Em vez disso, você encontrará código em Python em um script do tipo "text/python"
<p>Brython foi desenhado para substituir o Javascript como a linguagem de script da Web. Como tal, é uma implementação de Python 3 (você pode testar no <a href="console.html" id="c_pt">console</a>), adaptada ao ambiente HTML5, quer dizer, com uma interface para objetos e eventos DOM
<p>A <a href="/gallery/gallery_pt.html">galeria</a> apresenta algumas possibilidades, da criaçao de simples elementos de documentos até a ação de arrastar e soltar e navegação em 3D
</td>

<td style="padding-left:5%;">
<canvas width="250" height="250" id="clock">
<i>Desculpe, Brython não consegue fazer a demonstração funcionar em seu navegador, <br>verifique se o Javascript está ligado
<br><div id="navig_zone"></div></i>
</canvas>
</td>

</tr>

</table>

</div>


</body>
</html>
48 changes: 48 additions & 0 deletions src/one-liner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
(function() {
var scripts = document.getElementsByTagName("script")
//get last script that was executed (ie, this one!!!!!) and read
// data-brython-options if it exists..
var options = scripts[scripts.length-1].getAttribute("data-brython-options")

//figure out "root" path
var src = scripts[scripts.length-1].getAttribute("src")
var _path =src.split('/')
_path.pop()
_path = _path.join('/') + '/'

var _obj

if (options == null || options == '') {
_obj={debug:0}
} else {
try {
_obj=JSON.parse(options)
} catch(e) {
alert(e) // display an error to show that options cannot be parsed.
}
}

if (_obj.debug == 0 || _obj.debug==1) {
var _s = document.createElement('script');
_s.src = _path + "brython_dist.js";
_s.onload = function() { brython(_obj) };
document.head.appendChild(_s);
} else { // we will "import" each script individually so things can
// be debugged much easier by programmers/developers.

var _files=['brython_builtins', 'version_info', 'identifiers_re',
'py2js', 'py_object', 'py_type', 'py_utils',
'py_generator', 'py_builtin_functions',
'py_bytes', 'py_set', 'js_objects', 'stdlib_paths',
'py_import', 'py_string', 'py_int', 'py_float',
'py_complex', 'py_dict', 'py_list', 'py_dom']

for (var i=0; i < _files.length; i++) {
var _s = document.createElement('script');
_s.src = _path + _files[i] + '.js'
document.head.appendChild(_s);
}

document.body.onload = function() { brython(_obj) };
}
})();

0 comments on commit 541d373

Please sign in to comment.