Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, January 2, 2015

Innovation is not a hotdog

Once upon a time


You would walk in a supermarket, buy hot dogs and hot dog buns. It was a pretty straightforward process. Sausage pack, check. Buns, check.

Then, someone had the idea of making a bun length sausage. Hmm, ok, except that different brand of "bun length" sausages and buns all have different metrics. But hey, that's ok, it was a valiant effort.

More is more


Some time passed, and somebody thought, "hey, let's make a sausage longer than the bun!". Of course, all readers will be quick to point out that there never was a sausage exactly the length of a bun, they were either slightly shorter, or slightly longer. It was just a "more is more" marketing.

What's next


You are probably expecting a sausage to appear on the market "shorter than the bun!". And the circle will be complete. But, which one is the better design? Which one innovates? Same answer to both question: the original design for sausage, which dates back to at least the 9th century BC. Anything beyond that is in the presentation (the marketing).

Tech innovation


Now, back to technology. Let's take the phone, for example. Clearly, going wireless was an innovation. Going pocketable was an innovation. Touchscreen. Haptics. Innovations. But the same tech, just in a different (bigger and bigger, a.k.a. "more is more" marketing) package, is not innovation (*cough* apple *cough* samsung). In fact, one could say there is a clear regression in that field (phones used to have battery life expressed in weeks, could fit in your pocket, even in jogging shorts, could be dropped multiple times on rock hard surfaces without any problem etc)

You can do it


So, why am I talking about all of that? Well, it's my yearly encouragement to truly innovate (see last years post here). But you can't do it in a vacuum. Engage in your local community. If you haven't done so yet, make it a goal this year. Your local programing user groups (Python, Java, Javascript, whatever), maker space or hacker space, robotics, raspberry pi or other creative group, you local coworking, STEM/STEAM school groups etc. Not only will you benefit from attending, by growing your network and your knowledge, but you'll contribute something back to your community, to the society.

Before I sign off for the day, do read my post on innovation in general and personal scale innovation from last year.

@f_dion

Thursday, June 19, 2014

South East Linux Fest, Python Represent

Friday


I'll be presenting at South East Linux Fest (SELF) 2014. According to the final schedule, it is tomorrow, Friday the 20th at 4PM. Right after that will be a BOF in that same room. Come by and talk *nix and Python.

Last year Python was pretty much absent from the conference. Yet it is quite focused on security, and Python is just the right tool for that kind of stuff.

Brousse


That's one project among many I'll be talking about, bringing computing education to people who are usually left without.

Keep an eye on my twitter account and this blog for details. The core of the talk is about Brython.

Video


Apparently, videos of talks will be available after the conference.

@f_dion

Tuesday, March 25, 2014

Upcoming Python talk

Brython: Not Celtic, Pythonic!


Over the past few years, I've had a few A-Ha! moments, as I host project nights, mentor individuals and conduct workshops.

The latest was in front of a large classroom. That's when I realized I didn't have to explain what a shell or a command line was. So what is the Python punchline? It is one of the many anecdotes I'll cover in my talk @ TriPython this week in the Raleigh / Durham area of NC.

What

TriPython March meeting

Where

Bull City Coworking location detail

When

Thursday, March 27th
7PM


François
@f_dion

Sunday, February 9, 2014

Python everywhere: #Brython 2.0

 It's alive


Wow, 15 months later and we are at Brython 2.0!

Changes in Brython version 2.0-20140209-164925



Backwards-incompatible change

=============================
For the sake of namespace isolation, by default, the name of functions and classes defined in Brython are no more available in Javascript global namespace. As a consequence, functions can't be called as event callbacks from HTML tags. For instance, if a function echo() is defined in a Brython script, the following inline code :

    <button onclick="echo()">

will result in a Javascript error such as "name echo is not defined" when the button is clicked

The solution is to define the event callback inside Brython code. The button must have an id :

    <button id="echo">

and the Brython code must include the line

    doc["echo"].bind("click",echo)

Alternatively, to force the name "echo" into the global Javascript namespace, add it as an attribute of the window object :

    from browser import window
    window.echo = echo


Features

========
  • - namespace isolation : in previous versions, the names defined in Brython core scripts were included in the global Javascript namespace, raising risks of conflict with names defined in Javascript programs or libraries. In this version, the only names included in the global Javascript namespace are __BRYTHON__ (used internally) and brython(), the function called on page load
  • - implement sys.implementation with values adapted for Brython
  • - allow syntax del (x, y, z)
  • - use Dan McDougall's pyminifier to reduce size of py_VFS.js
  • - make_dist generates a script brython_dist.js that can be used as a standalone distribution on a centralised server.

Demos

=====
  • - add drop files demo (by Glenn Linderman) and French Python course (using module slideshow) to the gallery

Imports

=======
  • - improved version of py_VFS.js by Billy Earney. py_VFS compiles the standard library to make imports faster. Now packs Python source with JSON instead of base64

Built-in modules

================
  • - browser : add attributes "window" and "document" as alias of respectively "win" and "doc"
  • - add a module browser/slideshow for PowerPoint-like slideshows in Brython, using a custom file format

Bug fixes

=========
  • - issue #174 : string format character % has wrong precedence
  • - issue #175 : Functions should return None by default
  • - issue #183 : re.findall() broken
  • - issue #198 : operator precedence not defined for << and >>
  • - issue #206 : add <noscript> in case Javascript is disabled
  • - issue #208 : bug with try / else
  • - issue #209 : bug in ternary operator
  • - function definions must be evaluated only once, upon function definition
  • - bug with del a[:]
  • - bug with dir() called without arguments
  • - bug in map()
  • - bug with "func(x=1,)" ; "return +x" ; "func(10*-x)"
  • - bug in divmod and round
  • - bug in local_storage method keys()
  • - add attribute __doc__ to class and instance methods

Documentation

=============
  • - updated with the changes introduced in this version
  • - add documentation for the built-in module javascript
  • - translation in Spanish updated by Kiko Correoso

Thursday, August 22, 2013

From Java to Burma

Hands on Python


This month at our local Python user group (PYPTUG), I'll do a hands on session. Could have been in a workshop, code dojo or project night, but it'll be part of the normal monthly meeting.

Attributes, Properties and Descriptors


A lot of people learned C++ or Java in school and some of the normal patterns for these languages are regularly seen in the wild in languages such as C# and Python. Having coded in all of these, and many more, I appreciate greatly some of the features of a given programming language. And when it comes to Python (as Roger Sessions said, paraphrasing Einstein), that "everything should be as simple as it can be, but no simpler".

 The hands on will focus on attributes, and how to keep it simple. And of course, how to get out of trouble, because you have to do something not so simple later, using properties and descriptors.

I will be posting to my bitbucket pyptug repository some material related to the talk, including a log of the interactive session we will be doing.

Audience will be ranging from people who have never coded, to people who have programmed in other languages, to python experts. I love a challenge.

François
@f_dion

Saturday, August 17, 2013

Brython 20130817-141536 published

Download Brython


A new version of Brython, Brython-20130817-141536, has just been published on the downloads page



Changes

Here are the main changes since the previous version :

- improved implementation of import, now supports packages : "import X.Y", "from X.Y import Z [as A]", "from . import X" (fixes issue 123)
- the iterator protocol now uses the standard methods __iter__() and __next__() on all types, including built-in types
- the "for" loop implementation has been changed to use these methods
- improved implementation of comprehensions : now uses global and local dictionaries (fixes issue 129)
- improved interactive console : http://brython.info/tests/interactive_mode.html
- partial support of built-in type "bytes"
- add missing HTML5 tags and DOM events
- change documentation in French, add a section for Brython-specific modules ; updated translation of documentation
- add a button on the Tests page to run all the tests in a row and report errors
- improvement to the markdown module : tags _ and * generate different HTML tags, as well as __ and **
- change implementation of the del keyword : now uses the method __del__() if it is defined

Bugs

  • - bug fixes :
. issue #78 : map() and filter() return iterator objects, not lists
. issue #124 : support of CSS attribute "float"
. issue #125 : add methods copy() and clear() to lists
. issue #126 : escaped quotes inside strings
. issue #127 : DOMNode instances comparison methods (__eq__ and __ne__)
. issue #128 : class inheritance
. bugs in conversion of JS objects in json.js and $JS2Py
. bug with iteration on DOMNode instances



Other


  • package organisation : move JSObject from py_dom.js to py_utils.js
  • gallery : add a demo of a solitaire game using SVG drag and drop


Feedback


As always, the Brython team looks forward to your feedback, particularly in terms of bug reports and also in sharing how you are using Brython, by joining and participating in the Brython forum.

We are quite interested in your experience on mobile devices (tablets etc) and embedded devices (Raspberry Pi, Beaglebone black, Cubieboard etc), particularly in conjunction with touchscreens, as we are about to bring further enhancements to Brython. So don't be shy and join the forum. Or at least contact me through my blog or on twitter.

François
@f_dion

Friday, August 2, 2013

A python interactive console in my blog

Brython modes

I had prepped a presentation on Brython for a Python conference and didn't want that to go to waste, so now, dear reader, you get to see all kinds of exclusive material I had made for it. (Don't worry, I'll have plenty more material for PyCarolinas 2013).

The difference is that this is a blog, not a talk, so it will be a good bit more non linear. I'm starting tonight with something very hands on, one of Brython's mode of deployment.

The Brython interactive mode

The brython.js script itself is not included in this page, so it is a hosted interactive mode. We will simply include an iframe to load an interactive console directly from brython.info. This is still quite experimental, as it is found under the tests/ section. It is now using most of my iframe box (was fixed some days back). But it does work pretty well already.

This is basically a zero install, just add the following in your web page and you'll get a brython interactive session (Edited 3-26-2014 to point to new location):  

<iframe src="http://www.brython.info/console.html" width="98%" height="400">Sorry... your browser doesn't support iframe. Time to upgrade or go to <a href="http://www.brython.info/console.html">http://www.brython.info/console.html</a> in a separate tab.</iframe>






So you should see a console above (wont work trough news aggregators). At the >>> | prompt, type:

x = input("yo")

Type the word me in the prompt dialog that will open. Make sure you type exactly that. So what do we have in x? Type the following:

print(x)

me - Ok, that's all nice, but not very exciting. So it does behave like a console. What else can we do?

import webbrowser

So now we have loaded the module webbrowser from the brython standard library (we will come back to that in a future article). Yeah, I know, mind bending, since we are client side. Let's use the module. Type the following:


webbrowser.open("http://en.wikipedia.com/wiki/internet_" + x*2)

Nice! All your base are belong to us, obviously. So, it does take a minute to get the brain wrapped around this concept, but once you do, the world's your oyster. You just have to:

doc <= "think"
:)

Alright, enough geek puns, but it is a friday night afterall. So go and check it all out at http://brython.info . There is documentation in english, french, spanish and portuguese. Feel free to contribute your own translations in markdown format through bitbucket.

If you've been following my blog, you already know about the <= (left arrow) operator. If not, check it out here: http://raspberry-python.blogspot.com/2012/12/brython-browser-python.html

In the early days, brython didn't have a print() keyword. So I had cooked up a quick webprint() that used the <= operator. Of course, 8 months later, we no longer need webprint(). Print works like it should, with stdout. For the interactive mode, it is redirected. Look at the (python) code to see how you can do that by right clicking on the iframe and doing a view frame source (hint, lines 48 to 51).


François
@f_dion


Wednesday, July 31, 2013

Site brython.info em portugues

Site

Algo novo hoje:

em portugues!

Documentação


O site juntamente com a documentação foi traduzido. Tudo graças aos esforços de Yuri Teixeira.

Grupo

Existe tambem um grupo googlegroups em portugues:

https://groups.google.com/forum/?fromgroups=#!forum/brython-pt

François
@f_dion
 

Friday, June 7, 2013

Brython a Toulon



Au programme de Pytong (http://pytong.org/orateurs.html) a Toulon, on retrouve une présentation de Brython (http://www.brython.info), avis aux intéressés!



François
@f_dion

Friday, February 1, 2013

Nouvelle publication DIY

faitmain

Un nouveau magazine vient de paraitre, il s'agit de Fait Main, un magazine collaboratif en ligne et en PDF:

http://www.faitmain.org

On y retrouve divers sujets autour du DIY("Do It Yourself"), et dans ce premier numéro, on y parle bien sur de Raspberry Pi.

J'ai écris l'article "câble d'interface pour Raspberry Pi" Lire l'article 

Mais ce n'est pas tout: 

Contenu du volume 1

La tribune de ce numéro est un parallèle entre web hébergé et OGM. Lire la tribune 

Le premier article présente une application de reconnaissance de feuille écrite pendant un Hackathon. C'est l'application qui a été écrite en 24 heures par Olivier, Ronan & Tarek lors du dernier AngelHack à Paris. On y parle de machine-learning au service des plantes, des hackathons de programmation & de responsive design . Lire l'article

Le deuxième article parle de domotique et vous explique comment piloter des dispositifs sans fils - portails, détecteurs de mouvements etc. On y parle d' Arduino , de Raspberry-PI et de signal en 433 mhz . Lire l'article 
 
Le troisième article présente le travail de Marcin Ignac: des méduses animées en 3D. Des captures d'écran de ces méduses ont ensuite été utilisées pour faire partie d'un projet de livre génératif. On y parle d' animation procédurale , de processing.js & d'hachurage. Lire l'article

Le quatrième article vous donne 5 conseils de photos culinaires pour que vous puissiez prendre en photos vos soupes, gigots et autres desserts comme un(e) pro. Lire l'article 

Suit une interview de Hugues Aubin au LabFab de Rennes. Lire l'article .

Un cinquième article sur la conception d'un Juke box avec un Raspberry-PI, sans aucune soudure requise :) Lire l'article 

Le sixième article vous explique comment recycler une vieille nappe de disque dur pour connecter le GPIO de votre Raspberry. Lire l'article 

Le septième article est une rapide présentation du jeu The Midst , conçu avec Processing et WebPD. Lire l'article 

Enfin, le huitième article aborde les bases du fonctionnement d'une CNC. Lire l'article 
Bonne Lecture!
— Tarek

Equipe

Le projet FaitMain est monté par Tarek Ziadé mais est surtout possible grâce aux créateurs d'articles et aux relecteurs.

Ont participé à ce numéro :

Tuesday, January 29, 2013

Applications pour téléphones mobiles avec Python

C'est une traduction de iPhone app with Python. J'ai eu une forte demande pour la version française.

Grâce a Brython


L’icône Brython GPS

 

Une vraie app pour iPhone?


Le programme lancé, on y voit un écran de démarrage, comme il se doit:

Splash (ancienne carte de Caroline du Nord)

Mais c'est un programme web, et pas une application faite avec xcode.

Le premier écran, mode manuel


Mode mise a jour automatique

J'essaie?


Il suffit d'aller sur le lien de la galerie de Brython, ici:

gallery/geo.html et sur un iPhone, on l'ajoute a l'ecran d'accueil. On peut maintenant lancer le programme comme une vraie application iOS.


J'ai déjà vu cela, non?


C'est bel et bien une application web, donc basée sur HTML et CSS, mais le code lui même, c'est écrit en Python. En plus, on utilise ici une toute nouvelle fonctionnalité de Brython, en faisant appel a un script Python externe a la page HTML (c'est une nouveauté qui date de cette fin de semaine), plutôt que d'avoir le code a même la page HTML. Cela nous permet une séparation de la présentation, de la logique et du "bling" (le CSS):

Notre HTML


<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <meta charset="iso-8859-1">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1,maximum-scale=1">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <script src="../brython.js"></script>
        <script type="text/python" src="navi.py"></script>
        <link rel="stylesheet" type="text/css" href="navi.css" />
        <link rel="apple-touch-icon" href="icon.png"/>
        <link rel="apple-touch-startup-image" href="splash.png">
    </head>
    <body onLoad="brython()">
        <div id="header">
            <H1>Votre position</H1>
            <div id="switch">
                  <span class="thumb"></span>
                    <input id="refr" type="checkbox" />
                </div>
            </div>
        </div>
        <div id="navarea"></div>
        <div id="maparea"></div>
    </body>
</html>

Application web pour iPhone typique, mais sans jQuery mobile ou autre module du genre. Et pas de onclick dans la page html. L'unique javascript c'est brython.js qui est l’interpréteur Brython même et l'appel a brython() par l'entremise de onload.

Le code Python n'est pas sur la page, mais on voit qu'on y fait reference par src="navi.py"

Allons donc voir ce qu'il y a dans ce fichier navi.py:

Notre Python


# globals #########################
refr = False
geo = win.navigator.geolocation
watchid = 0


# les fonctions ###########################
def navi(pos):
    xyz = pos.coords

    ul = UL(id="nav")
    ul <= LI('lat: %s' % xyz.latitude)
    ul <= LI('lon: %s' % xyz.longitude)

    mapurl = "http://maps.googleapis.com/maps/api/staticmap?markers=%f,%f&zoom=15&size=320x298&sensor=true" % (xyz.latitude, xyz.longitude)
    img = IMG(src = mapurl, id = "map")
    try:
        doc["nav"].html = ul.html  # on met a jour la liste
    except KeyError:
        doc["navarea"] <= ul  # on cree la liste
    try:
        doc["map"].src = mapurl  # on met a jour l'url de l'image
    except KeyError:
        doc["maparea"] <= img  # on cree la balise img

def nonavi(error):
    log(error)

def navirefresh(ev):
    global refr, watchid
    refr = False if refr else True
    if refr == True:
        doc["switch"].className = "switch on"
        watchid = geo.watchPosition(navi, nonavi)
    else:
        doc["switch"].className = "switch"
        geo.clearWatch(watchid)

# au demarrage ###########
if geo:
    geo.getCurrentPosition(navi, nonavi)
    doc["switch"].className = "switch"
    doc["switch"].onclick = navirefresh  # on associe un evenement onclick
else:
    alert('geolocation not supported')

On établis 2 fonctions de rappel (callback). Une si on a notre géolocalisation (navi), et une s'il y a une erreur (nonavi), et finalement, une autre fonction (navirefresh) pour s'occuper de l’événement onclick du contrôle auto refresh dans la barre de menu de l'application. Le démarrage initial se fait par un appel a geo.getCurrentPosition avec nos fonctions de rappel. Ça fonctionne assez bien comme GPS.

Notre CSS

Le CSS étant un peu long, je ne le mettrai pas sur mon blog, mais vous pouvez trouver le code sur le site brython.info ou sur googlecode: SVN repository. Le CSS pour l'interrupteur genre ios 5 a ete emprunté ici: ios-5-style-switch-control

Ce n'est que le début

Alors voila, c'est un point de depart pour faire toute sortes de choses. Un tracker pour le jogging, le velo (avec local storage et synchro par appel ajax) et bien d'autres choses. Vous pouvez désormais faire tout cela avec votre langage favori (Python, bien sur) que ce soit pour votre téléphone mobile ou tablette. Cet exemple est quelque peu spécifique au iPhone (surtout a cause du CSS), mais fonctionne sur Android aussi et peut être adapté facilement aux tablettes. Et cela ne m'a pas pris beaucoup de temps.

Et si vous avez besoin d'aide, n'oubliez pas qu'il existe une liste en francais:
forum/brython-fr

@f_dion

Monday, January 28, 2013

iPhone app with Python

Thanks to Brython


Brython GPS icon

 

Native? Not quite...


The application launches with a splashscreen, like it should

Splash page

But it is really a web application.

Tracking my progress
Automatically refreshes on movement

Can I try it?


Absolutely. Simply point your iphone to the brython gallery url:

gallery/geo.html then click add to home screen. You can now launch it like a native application.


What makes it special?


It's a web application, so of course HTML and CSS, but the code is Python. It leverages the new Brython feature to link to a remote python script, instead of having it inline with the html. This allows a clean separation of presentation, logic and eye candy:

The HTML


<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <meta charset="iso-8859-1">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1,maximum-scale=1">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <script src="../brython.js"></script>
        <script type="text/python" src="navi.py"></script>
        <link rel="stylesheet" type="text/css" href="navi.css" />
        <link rel="apple-touch-icon" href="icon.png"/>
        <link rel="apple-touch-startup-image" href="splash.png">
    </head>
    <body onLoad="brython(2)">
        <div id="header">
            <H1>Your position</H1>
            <div id="switch">
                  <span class="thumb"></span>
                    <input id="refr" type="checkbox" />
                </div>
            </div>
        </div>
        <div id="navarea"></div>
        <div id="maparea"></div>
    </body>
</html>

Your typical iPhone web application, except that there is no jQuery mobile or similar framework. There is no onclick. The only javascript is the brython.js file for Brython itself and the related body onload call of brython().

So let's have a look at the Python code:

The Python


# globals #########################
refr = False
geo = win.navigator.geolocation
watchid = 0


# functions ###########################
def navi(pos):
    xyz = pos.coords

    ul = UL(id="nav")
    ul <= LI('lat: %s' % xyz.latitude)
    ul <= LI('lon: %s' % xyz.longitude)

    mapurl = "http://maps.googleapis.com/maps/api/staticmap?markers=%f,%f&zoom=15&size=320x298&sensor=true" % (xyz.latitude, xyz.longitude)
    img = IMG(src = mapurl, id = "map")
    try:
        doc["nav"].html = ul.html
    except KeyError:
        doc["navarea"] <= ul
    try:
        doc["map"].src = mapurl
    except KeyError:
        doc["maparea"] <= img

def nonavi(error):
    log(error)

def navirefresh(ev):
    global refr, watchid
    refr = False if refr else True
    if refr == True:
        doc["switch"].className = "switch on"
        watchid = geo.watchPosition(navi, nonavi)
    else:
        doc["switch"].className = "switch"
        geo.clearWatch(watchid)

# the setup
if geo:
    geo.getCurrentPosition(navi, nonavi)
    doc["switch"].className = "switch"
    doc["switch"].onclick = navirefresh
else:
    alert('geolocation not supported')

We are setting up 2 callback functions. One called if we have navigation (navi) support, one if we dont (nonavi), and finally a function (navirefresh) to handle the onclick of the auto refresh switch in the title bar of the application. This works pretty decently as a quick and dirty GPS application.

The CSS

The CSS is a bit long so I'm not posting it on the blog, but you can check out the source at the brython.info site or on the SVN repository. The ios style switch CSS is borrowed from this article: ios-5-style-switch-control

The tip of the iceberg

So there you have it. You can now use your favorite language (Python, of course) to write applications for your mobile phone or tablet. This example is slightly iPhone specific (mostly due to CSS), but the same basic structure applies to a variety of mobile devices. And it took no time whatsoever to write this.

@f_dion

Sunday, January 27, 2013

Utopia Python (ou realidade?)

Utopia


Imagine um mundo onde você pode programar em Python, onde que você quer. Sim, ela existe para iPad, Android, iPhone, PC, Unix, Mac, Linux etc. Mas há uma área ...

Navegadores Web


Seria ótimo se nós não tem que usar Javascript. Nós colocamos na nossa página web, algo como:

<script type="text/python">
def lista(num):
    for i in range(num):
        print(i)

lista(10)
</script>

Ou talvez colocar o nosso código em um arquivo e fazer isso:

<script type="text/python" src="codigo.py"></script>


E ter um bom suporte para HTML5, SVG, eventos, callbacks...
Sim, é genial, sem dúvida. De qualquer forma pode parar de sonhar com uma utopia, o que!

Consola Navegador (Firefox fazer Ctrl-Shift-K, Chrome Ctrl-Shift-J, Safari Ctrl-Alt-I): Este é o código Python que foi executado.

Impossível!

É muito possível, graças Brython:

O que é isso?

Veja esta página ( http://www.brython.info/test/test_clock.html ), o você vai ver um relógio analógico. E o código fonte da página? Sim, é um programa em Python!

Sim, eu sei ... deixa sem palavras ...

@f_dion

P.S. Nós Telecharge brython.js aqui: brython/downloads e como usá-lo (english). Lista Brython em português: forum/brython-pt. Esta semana, vou publicar no meu blog um aplicativo para iPhone escrito com Brython.

Friday, January 25, 2013

Brython trouve son code...

Sur le serveur


Jusqu’à maintenant, en parlant de Brython, j'ai mis l'emphase sur le fait que tout roule du cote du client, dans la page web.

Sur ce blog, par exemple, j'inclus même brython.js a même le gabarit de blogger, pour figer la version. Tout est ici.

Et bien sur, le code Python lui meme se retrouve a l'interieur de la balise script:

<script type="text/python">
#le code python va ici
print("Et pourtant elle tourne")
</script>

Mais pourquoi le titre?


C'est pour introduire une nouvelle fonctionnalité de Brython, tout juste sortie du four! On peut maintenant utiliser la syntaxe:

<script type="text/python" src="script.py"></script>

Et le Brython va aller chercher script.py (ou tout autre script python que l'on spécifie) avec un appel ajax, sur le serveur (avec certains navigateurs comme Firefox, en fait meme pas besoin de serveur, on peut faire un file open de la page web et tout fonctionne localement). Sur un serveur, comme c'est avec ajax, bien sur le script se doit d’être sur le même domaine que la page web.

On pourra ainsi séparer notre structure (.html), nos embellissements (.css) et notre logique (.py).

@f_dion

Thursday, December 27, 2012

UTF-8, les accents et Python

Python 2

Avec Python 2.x (2.7.x sur Raspberry Pi), on peux utiliser les caractères accentués directement dans nos chaines de caractères. Par exemple:

machaine = u"je suis bien étonné, François!"



Le u devant la chaine indique que c'est en unicode.

Encodage

En plus de cela, il faut indiquer a l’éditeur l'encodage (car on n'utilise pas des valeurs hexa ou octales, mais bien les caractères eux-mêmes). On peut utiliser un encodage latin-1, ISO-8859 ou un autre qui semble émerger comme le plus courant: UTF-8.

Pour declarer cela dans notre fichier Python, il faudra commencer avec:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

ou
#!/usr/bin/env python
# vim: set fileencoding=utf-8

selon que l'on prefere la syntaxe emacs ou vim :)

Python 3

Avec Python 3.x, les chaines sont toutes Unicode, et donc plus besoin de mettre un u devant les chaines. Toutefois, il faut encore et toujours declarer notre encodage, comme ci dessus.


Brython

Et avec Python pour les navigateurs web (Brython)? Brython suis la syntaxe de Python 3, et donc on peut declarer une chaine Unicode, sans u:

CYR =  'АБЦДЕФГЧИЙКЛМНОПЯРСТУВЖХЫЗШЩЭЮЁЬЪ'
Dans ce cas ci, l'alphabet russe. Mais pas dans l'ordre naturel. Je l'ai mis ici dans l'ordre de l'alphabet latin, de façon phonétique.

Et l'encodage lui? On le fera a l'exterieur du script Python. On l'indique par l'entremise de HTML et meta:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Un éditeur HTML (genre Bluefish) va savoir quel encodage utiliser, et idem pour le navigateur web qui recevra cela.

Si vous etes curieux, voila le lien (ruskey.html) et le code de mon petit test de clavier phonétique pour le cyrillique (russe):


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="/brython.js"></script>
</head>
<body onload="brython()">
<h1>Phonetic cyrillic on QWERTY keyboard</h1>
Here is a little test, mapping latin characters on a keyboard to their phonetically equivalent characters in a cyrillic script, as used in Russian.
<p>
This demoes UTF-8 unicode, handling of keyboard events, and adding, modifying and deleting elements from the tree.
<script type="text/python">

"""
Phonetic ordering of cyrillic (фонетических упорядочение кириллицу)
We are matching the latin alphabet, uppercase, then lowercase
"""

CYR =  'АБЦДЕФГЧИЙКЛМНОПЯРСТУВЖХЫЗШЩЭЮЁЬЪабцдефгчийклмнопярстувжхызшщэюёьъ'
position = 0


def printkey(letter):
    global position
    try:
        span = doc[str(position)]
        span.value = letter
    except KeyError:
        doc <= SPAN(letter, id = str(position))
    position += 1


def deletekey():
    global position
    position -= 1
    if position < 0:
        position = 0
    else:
        del doc[str(position)]


def keydown(e):
    if not e:
        e = win.event
    key = e.keyCode
    offset = 65 if e.shiftKey else 32
    e.preventDefault()
    e.stopPropagation()
    log(key)
    if key == 8:
        deletekey()
    elif key == 32:
        printkey(' ')
    elif key in range(48, 58):
        printkey(str(key - 48))
    elif key >= offset:
        printkey(CYR[key - offset])


def keyup(e):
    if not e:
        e = win.event
    e.preventDefault()
    e.stopPropagation()


def drawkeyboard():
    table = TABLE()
    row = TR()
    for letter in CYR:
        row <= TD(BUTTON(letter, onClick= "printkey('%s')" % letter))
        if letter in ('Я','Ъ','я'):
            table <= row
            row=TR()
    table <= row
    doc <= table


# Draw keyboard and set key events

drawkeyboard()
doc.onkeydown = keydown
doc.onkeyup = keyup

</script>
<br />
Click buttons or type on keyboard:
<br />
</body>
</html>

print() and win.print()

Python vs Brython vs Javacript


Before Python 3, print was a keyword, and not a function. With Python 3, print() is a built-in function.

Brython follows the syntax of Python 3, so one would expect a print() function. However that since its inception, it has been suggested that print() didn't make sense in the context of a web browser, and to use log() instead. win.print() was the call to the window.print() Javascript equivalent:

Javascript has a print() function too. It is actually a method of window, and brings up a print dialog to print a web page from a web browser.

The lightbulb moment

I didn't see it coming, but as Pierre was working with the Brython demo console (and I'm guessing from feedback from people who got confused by it) and thought that perhaps print() wasn't such a bad idea after all.

And here's what he came up with:
- for standard output there was a Brython-specific builtin function log() : it is now replaced by the usual Python function print(), with the syntax used in Python 3, including the keyword argument "end"
By default, print() sends its arguments to the browser console. This can be changed by setting sys.stdout to an object with a method write(). For instance, in the online console, to send the output to the textarea with the id "console" the code is (remember that classes are not implemented yet...)


import sys
sys.stdout = object()
def write(data):
    doc["console"].value += data
sys.stdout.write = write

Errors can also be redirected using sys.stderr

sys.stderr = object()
sys.stderr.write = write

But what about the javascript functionality of print(), did we loose that at the same time?

Thankfully, Pierre didn't hardwire conversion of keywords without keeping in mind the scope, and that means that the following works:


<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <script src="brython.js"></script>
    </head>
    <body onLoad="brython()">
        <script type="text/python">
        def printandprint():
            print("hello")
            win.print()

        doc <= BUTTON('Print and print', onClick='printandprint()')
        </script>
    </body>
</html>

You'll see in your debug console the word hello printed through print("hello"), and a print dialog will open when win.print() is called.

Try it:
 

Monday, December 24, 2012

Geolocation with Brython

Brython keywords

We used the doc keyword previously, in another article. How about using the win keyword this time? How about something for mobile apps?

Geolocation

To access geolocation services in your web browser, in Javascript you need to use the methods of window.navigator.geolocation. That means win.navigator.geolocation in Brython.

I'm lazy, so i'll assign it once:

geo = win.navigator.geolocation

Next I'll define a callback function for success and error:

def navi(pos):
    log('Position acquired')
    xyz = pos.coords
    display = "Your position: %f,%f" % (xyz.latitude, xyz.longitude)
    alert(display)
    log(pos.timestamp)
    log(xyz.latitude)
    log(xyz.longitude)
    log(xyz.accuracy)
    log(xyz.altitude)
    log(xyz.altitudeAccuracy)
    log(xyz.heading)
    log(xyz.speed)

def nonavi(error):
    log(error)

Alright, now we are ready to actually try to get a position:

if geo:
    geo.getCurrentPosition(navi, nonavi)
else:
    alert('geolocation not supported')

Full code

It is pretty straightforward:

<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <script src="brython.js"></script>
    </head>
    <body onLoad="brython()">
        <script type="text/python">
        geo = win.navigator.geolocation

        def navi(pos):
            log('Position acquired')
            xyz = pos.coords
            display = "Your position: %f,%f" % (xyz.latitude, xyz.longitude)
            alert(display)
            log(pos.timestamp)
            log(xyz.latitude)
            log(xyz.longitude)
            log(xyz.accuracy)
            log(xyz.altitude)
            log(xyz.altitudeAccuracy)
            log(xyz.heading)
            log(xyz.speed)

        def nonavi(error):
            log(error)

        if geo:
            geo.getCurrentPosition(navi, nonavi)
        else:
            alert('geolocation not supported')
        </script>
    </body>
</html>

Friday, December 21, 2012

Python List comprehensions now in Brython

Brython improvements

So by now, you've heard of Brython, the implementation of Python 3 (or at least a subset) for your web browser, in Javascript. After all, I've been talking about it for almost a month now (although not in english).

New this week


Pierre has been busy... He implemented the ternary operator, that is, a way to assign one of two values, based on a condition, for example:

x = 7 if a > 2 else 17
List comprehensions are also in! This was a heavily requested feature that was missing from Brython, for example:

y = [ x ** 2 for x in range(10)]
 I did find a bug in some variations, and am looking into the code to fix this.

Another addition this week is that your python code indentation is now relative to the first line of your script, instead of having to start at the first position. That means you can now format your html code and have your Python properly aligned:

<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <script src="brython.js"></script>
    </head>
    <body onLoad="brython()">
        <script type="text/python">
        def myfunc():
            return True

        log(myfunc())
        </script>
    </body>
</html>

instead of:
        <script type="text/python">
def myfunc():
    return True

log(myfunc())
        </script>


Sunday, December 16, 2012

Python en todo lugar

Ordenadores, móvil, navegadores

Empecé a programar ordenadores con el lenguaje Basic y Turtle (Logo) y poco después con Assembler, Pascal, C, C++ y un montón de otros lenguajes. En los anos 90, seguí con Perl, Java y Javascript (y varios otros a través los años como PHP, C#, Python, Ruby).

La mayoría del código que estoy escribiendo ahora es en Python, pero cuando es una cuestión de web, siempre hay que hacer algo en Javascript. Casi todas las paginas en la red incluyen <script...>.

type=text

En el pasado (mas de 10 anos atrás) era común ver <script type="text/vbscript"> (vbscript es una forma de visual basic), pero como solo Internet Explorer ofrece eso, no se ve mucho. Si hacemos algo que opera con todos los navegadores, debemos utilizar <script type="text/javascript">.

Ah, si tan sólo pudiéramos utilizar Python aquí también, del lado del navegador. Un lenguaje en todo lugares y todos los navegadores.

Si era posible...

Debería ser similar a la manera que uno puede usar Javascript. Una pagina html muy sencilla como la siguiente:

<html>
<head></head>
<body>
<script type="text/python">
def hola(nombre = "todo el mundo"):
    alert( "hola, " + str(nombre))  # numeros o caracteres

</script> 
<input type=button onclick="hola()" value="mundo!"> 
<input type=button onclick="hola('queridos lectores')" value="click!">
</body>
</html>

Incluso sin requerir un servidor. Sería bastante bien.


Si, ¡Es posible!

Hay dos cosas mas que debemos hacer, y funcionara:

<html>
<head><script src="brython.js"></script></head>
<body onload="brython()">
<script type="text/python">
def hola(nombre = "todo el mundo"):
    alert( "hola, " + str(nombre))  # numeros o caracteres


</script>

<input type=button onclick="hola()" value="mundo!">
<input type=button onclick="hola('queridos lectores')" value="click!">
</body>
</html>


Y, si estas leyendo mi sitio directamente en un ordenador o ipad (o similar), puedes probarlo (voy a añadir brython en mi sitio para móvil en unas semanas):


 
¡Demasiado! Es cierto.

Brython

Lo que hace eso posible es Brython:


Brython es un proyecto que tiene por objeto sustituir Python a Javascript en los navegadores web. Pierre Quentel annuncio el proyecto en el grupo fr.comp.lang.python ( annuncio en francés ) el 25 de noviembre.

De inmediato fue muy obvio para mi de que era lo que estaba buscando. Como he encontrado algunos problemas, los envió a Pierre, y él los corregía rápidamente. Le ayudo también con la traducción del sitio de francés a ingles:

brython.info/index_en.html

Ahora, estoy trabajando a traducir el sitio (toda la documentación) en español (y buscando ayuda).

No hay documentacion en español, pero hay una lista en español , un grupo google:

groups.google.com/forum/?fromgroups=#!forum/brython-es

Hay grupos google en ingles (brython) y frances (brython-fr) también.

Galeria

A veces una imagen vale mil palabras, o, en este caso, un sitio de demo:

reloj analógico
técnica 'arrastrar y soltar'
almacenamiento local
laberinto 3d


Haga un clic con el botón derecho para ver el código de cada demo. Python. Deja uno sin palabras, ¿verdad?


François