Blog entries

  • Sprint CubicWeb chez Logilab - annonce de dernière minute

    2010/04/29 by Arthur Lutz

    Logilab est en ce moment en train d'acceuillir un sprint autour de la plateforme CubicWeb. L'objectif principal de ce sprint de 5 jours est d'améliorer l'usage de javascript et des css dans CubicWeb :

    http://www.logilab.org/image/28586?vid=download http://codesnip.net/wp-content/uploads/javascript.png
    • avoir une API javascript propre, testée et documentée
    • pouvoir facilement changer le style d'une application cubicweb
    • gestion de bundle pour javascript et CSS
    • une documentation sur les standards d'écriture des fichiers JS et CSS pour cubicweb

    Ce sprint aura lieu du jeudi 29 avril 2010 au 5 mai 2010 (weekend exlus - les bureaux seront fermés). Vous êtes les bienvenus pour contribuer, filer un coup de main, faire du pair programming... ou simplement rencontrer des développeurs cubicweb. Vous pouvez même venir une après-midi ou une seule journée. Pour ceux avec des portables, il y aura du réseau disponible pour être connecté.

    Adresse : 104 Boulevard Auguste-Blanqui, Paris. Sonnez à "Logilab".

    Métro : St Jacques or Corvisart (Glacière est la station la plus proche mais sera fermée à partir de lundi)

    Contact : http://www.logilab.fr/contact

    Dates : du 29/04/2010 au 30/04/2010 et du 03/05/2010 au 05/05/2010


  • Javascript date support

    2008/11/27 by Adrien Di Mascio

    Coming from the python and mx.DateTime world, the javascript Date object is not really appealing. For me, the most disturbing things are :

    • The year parameter in the Date constructor is always considered as a XXe century year if year < 100. (this goes along with the getYear / getFullYear distinction).
    • The inconsistency between months and days indexes : months indexes starts at 0 whereas days indexes starts at 1.
    • The lack of decent strptime / strftime functions (even basic ones not taking locales into account).

    Recently, I've worked with the great Timeline project which makes an heavy use of dates and I had the need for a very basic strptime implementation. This can by no mean be considered as a comprehensive implementation, but it might help so here it is:

    var _DATE_FORMAT_REGXES = {
        'Y': new RegExp('^-?[0-9]+'),
        'd': new RegExp('^[0-9]{1,2}'),
        'm': new RegExp('^[0-9]{1,2}'),
        'H': new RegExp('^[0-9]{1,2}'),
        'M': new RegExp('^[0-9]{1,2}')
    }
    
    /*
     * _parseData does the actual parsing job needed by `strptime`
     */
    function _parseDate(datestring, format) {
        var parsed = {};
        for (var i1=0,i2=0;i1<format.length;i1++,i2++) {
        var c1 = format[i1];
        var c2 = datestring[i2];
        if (c1 == '%') {
            c1 = format[++i1];
            var data = _DATE_FORMAT_REGXES[c1].exec(datestring.substring(i2));
            if (!data.length) {
                return null;
            }
            data = data[0];
            i2 += data.length-1;
            var value = parseInt(data, 10);
            if (isNaN(value)) {
                return null;
            }
            parsed[c1] = value;
            continue;
        }
        if (c1 != c2) {
            return null;
        }
        }
        return parsed;
    }
    
    /*
     * basic implementation of strptime. The only recognized formats
     * defined in _DATE_FORMAT_REGEXES (i.e. %Y, %d, %m, %H, %M)
     */
    function strptime(datestring, format) {
        var parsed = _parseDate(datestring, format);
        if (!parsed) {
        return null;
        }
        // create initial date (!!! year=0 means 1900 !!!)
        var date = new Date(0, 0, 1, 0, 0);
        date.setFullYear(0); // reset to year 0
        if (parsed.Y) {
        date.setFullYear(parsed.Y);
        }
        if (parsed.m) {
        if (parsed.m < 1 || parsed.m > 12) {
            return null;
        }
        // !!! month indexes start at 0 in javascript !!!
        date.setMonth(parsed.m - 1);
        }
        if (parsed.d) {
        if (parsed.m < 1 || parsed.m > 31) {
            return null;
        }
        date.setDate(parsed.d);
        }
        if (parsed.H) {
        if (parsed.H < 0 || parsed.H > 23) {
            return null;
        }
        date.setHours(parsed.H);
        }
        if (parsed.M) {
        if (parsed.M < 0 || parsed.M > 59) {
            return null;
        }
        date.setMinutes(parsed.M);
        }
        return date;
    }
    
    // and now monkey patch the Timeline's parser ...
    /* provide our own custom date parser since the default
     * one only understands iso8601 and gregorian dates
     */
    Timeline.NativeDateUnit.getParser = function(format) {
        if (typeof format == "string") {
        if (format.indexOf('%') != -1) {
            return function(datestring) {
                if (datestring) {
                    return strptime(datestring, format);
                }
                return null;
            };
        }
            format = format.toLowerCase();
        }
        if (format == "iso8601" || format == "iso 8601") {
        return Timeline.DateTime.parseIso8601DateTime;
        }
        return Timeline.DateTime.parseGregorianDateTime;
    };
    

  • Simile-Widgets

    2008/08/07 by Nicolas Chauvat
    http://simile.mit.edu/images/logo.png

    While working on knowledge management and semantic web technologies, I came across the Simile project at MIT a few years back. I even had a demo of the Exhibit widget fetching then displaying data from our semantic web application framework back in 2006 at the Web2 track of Solutions Linux in Paris.

    Now that we are using these widgets when implementing web apps for clients, I was happy to see that the projects got a life of their own outside of MIT and became full-fledged free-software projects hosted on Google Code. See Simile-Widgets for more details and expect us to provide a debian package soon unless someone does it first.

    Speaking of Debian, here is a nice demo a the Timeline widget presenting the Debian history.

    http://beta.thumbalizr.com/app/thumbs/?src=/thumbs/onl/source/d2/d280583f143793f040bdacf44a39b0d5.png&w=320&q=0&enc=

  • Retour OSDC 2012 - présentation mercurial DVCS

    2012/12/05 by Pierre-Yves David

    À la mi-octobre, j'ai participé à la conférence OSDC 2012 à Paris. Le but de cette conférence est de permettre à des développeurs de différentes communautés de se rencontrer dans une ambiance chaleureuse. De fait, j'ai découvert un certain nombre de projets et de pratiques intéressants.

    http://act.osdc.fr/osdc2012fr/css/logo.png

    Le samedi, j'ai découvert des outils javascript mettant l'accent sur les modèles de données comme AngularJS ou BackBone, Une présentation rapide du langage Go, le très prometteur portage des outils GCC sur Windows nommé MinGW ainsi que les nouveautés de GCC 4.8. La journée s'est conclut sur des présentations éclairs dont je retiendrai surtout la perversité des opérateurs secrets en Perl et le livre Javascript Éloquent intégralement en HTML qui en profite donc pour inclure exemples et exercices interactifs au fil du contenu.

    Le dimanche matin j'ai ouvert le bal en présentant mes travaux actuels dans le DVCS Mercurial: l'Évolution de Changeset (PDF de la présentation). Ce concept permet aux développeurs de découvrir la réécriture d'historique de manière simple et sûre. Les utilisateurs avancés ont accès de leur côté à des processus de travail et de revue encore inédits dans le monde des DVCS. Ma présentation fut suivie d'une introduction à la découverte automatique de bugs grâce à la bisection dans les DVCS.


    Changesets Evolution : Mercurial secoue le monde du dvcs par Pierre-Yves David

    La journée s'est poursuivie avec une présentation du langage Haskell, de la bibliothèque de visualisation sigmajs et la spécification SPORE apportant un peu d'espoir dans les spécifications de services Web REST.


  • BestOfWeb 2015

    2015/06/11 by Adrien Di Mascio

    Nous étions à la journée BestOfWeb 2015 vendredi. Au programme, quelques unes des présentations jugées les plus intéressantes qui avaient été faites lors de différents meetups orientés "web" ces derniers mois.

    http://photos4.meetupstatic.com/photos/event/3/8/3/2/global_434894386.jpeg

    Même si j'aurais pu me passer des nombreuses interventions des sponsors et si toutes les présentations n'ont pas retenu mon attention, j'ai dans l'ensemble bien apprécié la journée. Voilà en particulier ce que je retiens :

    • angular n'a plus beaucoup de défenseurs, ou alors ils crient moins fort que les autres. De notre côté, après l'avoir utilisé pour construire quelques applications, la mauvaise documentation, la difficulté à conserver l'application maintenable et le fait qu'angular 2 — qui aura certainement plein de qualités — ne laisse pas de perspective de migration simple du code nous ont amenés à préférer des bibliothèques plus simples comme Backbone ;

    • Microsoft continue à contribuer du code libre et poursuit sa reconquête des développeurs perdus ;

    • j'aurais bien aimé voir Hydra mentionné dans la présentation REST,

    • j'étais resté sur l'utilisation de Accept-Ranges et Range dans le cadre de contenus binaires et je découvre (!) que ça semble être une pratique courante de les utiliser pour la pagination dans les API REST. À utiliser dans CubicWeb ?

    • CSS Grid Layout n'a pas l'air parti pour être utilisable avant un petit moment ;

    • l'an dernier, dans le cadre d'une collaboration avec l'itemm, nous avions fait de l'acquisition audio dans le navigateur. Nous testions la justesse d'instruments à vents et affichions les instruments en 3D dans le navigateur. Je me souviens qu'il fallait utiliser les nightly builds de chrome pour que ça fonctionne. Mais la présentation de l'ircam a montré que l'api Web Audio décollait vraiment. Ils ont fait des démonstrations de mixage en direct et on est passé à deux doigts de faire faire du sound painting à l'assemblée à coups de téléphones portables et websockets. Leur dépôt GitHub vaut le détour ;

      /file/293356/raw
    • RxJS et ses cousins BaconJS et KefirJS permettent d'écrire des traitements de flux d'information assez simplement à partir d'événements, de promesses et de plein d'autres choses.

    Et CubicWeb dans tout ça ? Et bien tout ça m'a donné envie de continuer activement le travail entamé sur le javascript utilisé dans CubicWeb. J'aimerais notamment qu'on puisse écrire de l'ES 6, qu'en mode debug, les fichiers soient transpilés à coups de babel (-- watch) et qu'on transpile également à la construction des paquets. On pourrait par la même occasion définir la liste des fonctionnalités "futures" qu'on s'autorise à utiliser dans le cœur de CubicWeb et pour lesquelles CubicWeb fournirait des polyfills si besoin (promesses, fetch, fileAPI, etc.).

    Pour conclure, félicitations aux organisateurs pour avoir su trouver une autre salle à la dernière minute et pour la qualité de la journée dans son ensemble. Sans doute à l'an prochain et pour certains d'entre eux à bientôt à WebGL Paris


  • 3D Visualization of simulation data with x3dom

    2016/02/16 by Yuanxiang Wang

    X3DOM Plugins

    As part of the Open Dream Kit project, we are working at Logilab on the creation of tools for mesh data visualization and analysis in a web application. Our goal was to create widgets to use in Jupyter notebook (formerly IPython) for 3D visualization and analysis.

    We found two interesting technologies for 3D rendering: ThreeJS and X3DOM. ThreeJS is a large JavaScript 3D library and X3DOM a HTML5 framework for 3D. After working with both, we chose to use X3DOM because of its high level architecture. With X3DOM the 3D model is defined in the DOM in HTML5, so the parameters of the nodes can be changed easily with the setAttribute DOM function. This makes the creation of user interfaces and widgets much easier.

    We worked to create new DOM nodes that integrate nicely in a standard X3DOM tree, namely IsoColor, Threshold and ClipPlane.

    We had two goals in mind:

    1. create an X3DOM plugin API that allows one to create new DOM nodes which extend X3DOM functionality;
    2. keep a simple X3DOM-like interface for the final users.

    Example of the plugins Threshold and IsoColor:

    image0

    The Threshold and IsoColor nodes work like any X3DOM node and react to attribute changes performed with the setAttribute method. This makes it easy to use HTML widgets like sliders / buttons to drive the plugin's parameters.

    X3Dom API

    The goal is to create custom nodes that affect the rendering based on data (positions, pressure, temperature...). The idea is to manipulate the shaders, since it gives low-level manipulation on the 3D rendering. Shaders give more freedom and efficiency compared to reusing other X3DOM nodes. (Reminder : Shaders are parts of GLSL, used to work with the GPU).

    X3DOM has a native node to all users to write shaders : the ComposedShader node. The problem of this node is it overwrites the shaders generated by X3DOM. For example, nodes like ClipPlane are disabled with a ComposedShader node in the DOM. Another example is image texturing, the computation of the color from texture coordinate should be written within the ComposedShader.

    In order to add parts of shader to the generated shader without overwriting it I created a new node: CustomAttributeNode. This node is a generic node to add uniforms, varying and shader parts into X3DOW. The data of the geometry (attributes) are set using the X3DOM node named FloatVertexAttribute.

    Example of CustomAttributeNode to create a threshold node:

    image2

    The CustomAttributeNode is the entry point in x3dom for the javascript API.

    JavaScript API

    The idea of the the API is to create a new node inherited from CustomAttributeNode. We wrote some functions to make the implementation of the node easier.

    Ideas for future improvement

    There are still some points that need improvement

    • Create a tree widget using the grouping nodes in X3DOM
    • Add high level functions to X3DGeometricPropertyNode to set the values. For instance the IsoColor node is only a node that set the values of the TextureCoordinate node from the FloatVertexAttribute node.
    • Add high level function to return the variable name needed to overwrite the basic attributes like positions in a Geometry. With my API, the IsoColor use a varying defined in X3DOM to overwrite the values of the texture coordinate. Because there are no documentation, it is hard for the users to find the varying names. On the other hand there are no specification on the varying names so it might need to be maintained.
    • Maybe the CustomAttributeNode should be a X3DChildNode instead of a X3DGeometricPropertyNode.

    image4

    This structure might allow the "use" attribute in X3DOM. Like that, X3DOM avoid data duplication and writing too much HTML. The following code illustrate what I expect.

    image5


  • ngReact: getting angular and react to work together

    2016/08/03 by Nicolas Chauvat

    ngReact is an Angular module that allows React components to be used in AngularJS applications.

    I had to work on enhancing an Angular-based application and wanted to provide the additionnal functionnality as an isolated component that I could develop and test without messing with a large Angular controller that several other people were working on.

    Here is my Angular+React "Hello World", with a couple gotchas that were not underlined in the documentation and took me some time to figure out.

    To set things up, just run:

    $ mkdir angulareacthello && cd angulareacthello
    $ npm init && npm install --save angular ngreact react react-dom
    

    Then write into index.html:

    <!doctype html>
    <html>
         <head>
                 <title>my angular react demo</title>
         </head>
         <body ng-app="app" ng-controller="helloController">
                 <div>
                         <label>Name:</label>
                         <input type="text" ng-model="person.name" placeholder="Enter a name here">
                         <hr>
                         <h1><react-component name="HelloComponent" props="person" /></h1>
                 </div>
         </body>
         <script src="node_modules/angular/angular.js"></script>
         <script src="node_modules/react/dist/react.js"></script>
         <script src="node_modules/react-dom/dist/react-dom.js"></script>
         <script src="node_modules/ngreact/ngReact.js"></script>
         <script>
         // include the ngReact module as a dependency for this Angular app
         var app = angular.module('app', ['react']);
    
         // define a controller that has the name attribute
         app.controller('helloController', function($scope) {
                 $scope.person = { name: 'you' };
         });
    
         // define a React component that displays "Hello {name}"
         var HelloComponent = React.createClass({
                 render: function() {
                         return React.DOM.span(null, "Hello "+this.props.name);
                 }
         });
    
         // tell Angular about this React component
         app.value('HelloComponent', HelloComponent);
    
         </script>
    </html>
    

    I took me time to get a couple things clear in my mind.

    <react-component> is not a React component, but an Angular directive that delegates to a React component. Therefore, you should not expect the interface of this tag to be the same as the one of a React component. More precisely, you can only use the props attribute and can not set your react properties by adding more attributes to this tag. If you want to be able to write something like <react-component firstname="person.firstname" lastname="person.lastname"> you will have to use reactDirective to create a specific Angular directive.

    You have to set an object as the props attribute of the react-component tag, because it will be used as the value of this.props in the code of your React class. For example if you set the props attribute to a string (person.name instead of person in the above example) , you will have trouble using it on the React side because you will get an object built from the enumeration of the string. Therefore, the above example can not be made simpler. If we had written $scope.name = 'you' we could not have passed it correctly to the react component.

    The above was tested with angular@1.5.8, ngreact@0.3.0, react@15.3.0 and react-dom@15.3.0.

    All in all, it worked well. Thank you to all the developers and contributors of these projects.


  • SciviJS

    2016/10/10 by Martin Renou

    Introduction

    The goal of my work at Logilab is to create tools to visualize scientific 3D volumic-mesh-based data (mechanical data, electromagnetic...) in a standard web browser. It's a part of the european OpenDreamKit project. Franck Wang has been working on this subject last year. I based my work on his results and tried to improve them.

    Our goal is to create widgets to be used in Jupyter Notebook (formerly IPython) for easy 3D visualization and analysis. We also want to create a graphical user interface in order to enable users to intuitively compute multiple effects on their meshes.

    As Franck Wang worked with X3DOM, which is an open source JavaScript framework that makes it possible to display 3D scenes using HTML nodes, we first thought it was a good idea to keep on working with this framework. But X3DOM is not very well maintained these days, as can be seen on their GitHub repository.

    As a consequence, we decided to take a look at another 3D framework. Our best candidates were:

    • ThreeJS
    • BabylonJS

    ThreeJS and BabylonJS are two well-known Open Source frameworks for 3D web visualization. They are well maintained by hundreds of contributors since several years. Even if BabylonJS was first thought for video games, these two engines are interesting for our project. Some advantages of ThreeJS are:

    Finally, the choice of using ThreeJS was quite obvious because of its Nodes feature, contributed by Sunag Entertainment. It allows users to compose multiple effects like isocolor, threshold, clip plane, etc. As ThreeJS is an Open Source framework, it is quite easy to propose new features and contributors are very helpful.

    ThreeJS

    As we want to compose multiple effects like isocolor and threshold (the pixel color correspond to a pressure but if this pressure is under a certain threshold we don't want to display it), it seems a good idea to compose shaders instead of creating a big shader with all the features we want to implement. The problem is that WebGL is still limited (as of the 1.x version) and it's not possible for shaders to exchange data with other shaders. Only the vertex shader can send data to the fragment shader through varyings.

    So it's not really possible to compose shaders, but the good news is we can use the new node system of ThreeJS to easily compute and compose a complex material for a mesh.

    alternate text

    It's the graphical view of what you can do in your code, but you can see that it's really simple to implement effects in order to visualize your data.

    SciviJS

    With this great tools as a solid basis, I designed a first version of a javascript library, SciviJS, that aims at loading, displaying and analyzing mesh data in a standard web browser (i.e. without any plugin).

    You can define your visualization in a .yml file containing urls to your mesh and data and a hierarchy of effects (called block structures).

    See https://demo.logilab.fr/SciviJS/ for an online demo.

    You can see the block structure like following:

    https://www.logilab.org/file/8719790/raw

    Data blocks are instantiated to load the mesh and define basic parameters like color, position etc. Blocks are connected together to form a tree that helps building a visual analysis of your mesh data. Each block receives data (like mesh variables, color and position) from its parent and can modify them independently.

    Following parameters must be set on dataBlocks:

    • coordURL: URL to the binary file containing coordinate values of vertices.
    • facesURL: URL to the binary file containing indices of faces defining the skin of the mesh.
    • tetrasURL: URL to the binary file containing indices of tetrahedrons. Default is ''.
    • dataURL: URL to the binary file containing data that you want to visualize for each vertices.

    Following parameters can be set on dataBlocks or plugInBlocks:

    • type: type of the block, which is dataBlock or the name of the plugInBlock that you want.
    • colored: define whether or not the 3D object is colored. Default is false, object is rendered gray.
    • colorMap: color map used for coloration, available values are rainbow and gray. Default is rainbow.
    • colorMapMin and colorMapMax: bounds for coloration scaled in [0, 1]. Default is (0, 1).
    • visualizedData: data used as input for coloration. If data are 3D vectors available values are magnitude, X, Y, Z, and default is magnitude. If data are scalar values you don't need to set this parameter.
    • position, rotation, scale: 3D vectors representing position, rotation and scale of the object. Default are [0., 0., 0.], [0., 0., 0.] and [1., 1., 1.].
    • visible: define whether or not the object is visible. Default is true if there's no childrenBlock, false otherwise.
    • childrenBlocks: array of children blocks. Default is empty.

    As of today, there are 6 types of plug-in blocks:

    • Threshold: hide areas of your mesh based on a variable's value and bound parameters

      • lowerBound: lower bound used for threshold. Default is 0 (representing dataMin). If inputData is under lowerBound, then it's not displayed.
      • upperBound: upper bound used for threshold. Default is 1 (representing dataMax). If inputData is above upperBound, then it's not displayed.
      • inputData: data used for threshold effect. Default is visualizedData, but you can set it to magnitude, X, Y or Z.
    • ClipPlane: hide a part of the mesh by cutting it with a plane

      • planeNormal: 3D array representing the normal of the plane used for section. Default is [1., 0., 0.].
      • planePosition: position of the plane for the section. It's a scalar scaled bewteen -1 and 1. Default is 0.
    • Slice: make a slice of your mesh

      • sliceNormal
      • slicePosition
    • Warp: deform the mesh along the direction of an input vector data

      • warpFactor: deformation factor. Default is 1, can be negative.
      • inputData: vector data used for warp effect. Default is data, but you can set it to X, Y or Z to use only one vector component.
    • VectorField: represent the input vector data with arrow glyphs

      • lengthFactor: factor of length of vectors. Default is 1, can be negative.
      • inputData
      • nbVectors: max number of vectors. Default is the number of vertices of the mesh (which is the maximum value).
      • mode: mode of distribution. Default is volume, you can set it to surface.
      • distribution: type of distribution. Default is regular, you can set it to random.
    • Points: represent the data with points

      • pointsSize: size of points in pixels. Default is 3.
      • nbPoints
      • mode
      • distribution

    Using those blocks you can easily render interesting 3D scenes like this:

    https://www.logilab.org/file/8571787/raw https://www.logilab.org/file/8572007/raw

    Future works

    • Integration to Jupyter Notebook
    • As of today you only can define a .yml file defining the tree of blocks, we plan to develop a Graphical User Interface to enable users to define this tree interactively with drag and drop
    • Support of most file types (for now it only supports binary files)