dimanche 30 décembre 2012

ASCII printing of Clojure's datastructures

Printing Clojure's datastructures as graphs using vijual


cljsta.graph> (draw-tree [[:north-america [:usa [:miami]
                                                [:seattle]
                                                [:idao [:boise]]]]
                          [:europe [:germany]
                                   [:france [:paris]
                                            [:lyon]
                                            [:cannes]]]])
        +------------+        +--------+
        |    north   |        | europe |
        |   america  |        +---+----+
        +-----+------+            |
              |         +---------+---------+
              +         |                   |
              |    +----+----+          +---+----+
           +--+--+ | germany |          | france |
           | usa | +---------+          +---+----+
           +--+--+                          |
              |                    +--------+---------+
    +---------++---------+         |        |         |
    |          |         |     +---+---+ +--+---+ +---+----+
+---+---+ +----+----+ +--+---+ | paris | | lyon | | cannes |
| miami | | seattle | | idao | +-------+ +------+ +--------+
+-------+ +---------+ +--+---+
                         |
                         +
                         |
                     +---+---+
                     | boise |
                     +-------+
nil

Pretty printing tables using Clojure core lib

cljsta.graph> (clojure.pprint/print-table [{:a 1 :b 2 :c 3} {:b 5 :a 7 :c "dog"}])

=============
:a | :c  | :b
=============
1  | 3   | 2
7  | dog | 5
=============
nil

Pretty printing tables using cldwalker / table


cljsta.graph> (table (meta #'doc))
+-----------+---------------------------------------------------------------+
| key       | value                                                         |
+-----------+---------------------------------------------------------------+
| :macro    | true                                                          |
| :ns       | clojure.repl                                                  |
| :name     | doc                                                           |
| :arglists | ([name])                                                      |
| :added    | 1.0                                                           |
| :doc      | Prints documentation for a var or special form given its name |
| :line     | 120                                                           |
| :file     | clojure/repl.clj                                              |
+-----------+---------------------------------------------------------------+
nil

Pretty printing tables using joegallo / doric

https://github.com/joegallo/doric

cljsta.lib-example.joegallo-table> (println (table [{:a 1 :b 2}]))
|---+---|
| A | B |
|---+---|
| 1 | 2 |
|---+---|
nil

It even have barcharts! (I love this one):

cljsta.lib-example.joegallo-table> (defn trunc [x] (double (/ (int (* 100 x))
                                                              100)))
#'cljsta.lib-example.joegallo-table/trunc
cljsta.lib-example.joegallo-table> (defn gauss [x] (/ (Math/exp (- (* 1/2 x x)))
                                                      (Math/sqrt (* 2 Math/PI)))
                                                      )
#'cljsta.lib-example.joegallo-table/gauss
cljsta.lib-example.joegallo-table> (println (table ^{:format raw}
                                                 [:x {:name :y :format bar}]
                                                 (map (fn [x] {:x (trunc x) :y (int (* 80 (gauss x)))}) (range -2.8 2.8 0.15))
                                                 ))
  X                  Y
-2.8
-2.65
-2.5  #
-2.35 ##
-2.2  ##
-2.05 ###
-1.9  #####
-1.75 ######
-1.6  ########
-1.45 ###########
-1.3  #############
-1.15 ################
-1.0  ###################
-0.85 ######################
-0.7  ########################
-0.55 ###########################
-0.4  #############################
-0.25 ##############################
-0.1  ###############################
0.04  ###############################
0.19  ###############################
0.34  ##############################
0.49  ############################
0.64  #########################
0.79  #######################
0.94  ####################
1.09  #################
1.24  ##############
1.39  ###########
1.54  #########
1.69  #######
1.84  #####
1.99  ####
2.14  ###
2.29  ##
2.44  #
2.59  #
2.74
nil







dimanche 21 octobre 2012

lazyposse genesis

We decided to change the name of our github organisation



  • from "clojure-consulting" (ridiculous I know) 
  • to lazyposse (still ridiculous, but cooler).


New name, new logo!

Lets grab our tools...




My two first origamis

A rabbit



A scarab




How does this relate to computer programming?


I don't know how this relate to computer programming, except that in either case we start from an unlimited resource (bits or pieces of paper), and if done well, we can achieve something cool. 

samedi 20 octobre 2012

emacs-live + tmux: Yes we can!

emacs-live is gorgeous:





But under tmux it can look like this:






Let's fix it!



Note: I'm using Ubuntu Linux, if you're using another distro / OS, it may or may not work.



Does your terminal support 256 colors?


./256colors2.pl
  • If it shows something like the following, you should be good (this is gnome-terminal):


Force tmux to 256 colors


  • In a terminal run tmux
  • And the 256colors2.pl script again:
./256colors2.pl
  • I'm getting this:


  • If it's the case run tmux with the -2 option to force 256 colors:
tmux -2
  • After that:



Tell Emacs to use 256 colors


  • In the previousely setup tmux session, run Emacs in CLI mode: emacs -nw
  • Then M-x list-color-display
  • I'm getting:


  • We need to make Emacs aware of the 256 colors support
  • Exit Emacs
  • In the terminal:
export TERM=screen-256color
  • Run Emacs again, and M-x list-color-display
  • You're good if you get something like:


I want a really black background!


Things are better, but not perfect: Emacs have a grey-ish background instead of black.
  • In Emacs: M-x list-color-display:


  • Note the name of the black color, for me here it's color-16
  • Eval the following to get a black background: M-:
(set-face-background 'default "color-16")
  • You should have:


Finally ^_^





Date: 2012-10-20 18:23:37 CEST
Author: denis
Org version 7.8.09 with Emacs version 24
Validate XHTML 1.0

dimanche 15 avril 2012


Injecting a Clojure REPL into your Existing Java Web app

What?

  • You develop an existing Java Web app
  • You would like to tinker with it using Clojure
  • And to connect to it from Emacs to mess around the live Web app
Let's do that!

The existing Java Web app

For this example, must be Mavenized, must have the Jetty plugin.
This maven archetype has that:
mvn archetype:generate \
-DarchetypeGroupId=org.cometd.archetypes \
-DarchetypeArtifactId=cometd-archetype-jquery-jetty6 \
-DgroupId=cljinject \
-DartifactId=cljinject
Check it's running correctly with:
cd cljinject
mvn jetty:run
You should have something on http://localhost:8080/cljinject

Add the clojars repository

Clojars is where all the Clojure goodies lives.
Add to your pom.xml:
<version>1.0-SNAPSHOTversion>

<repositories>
  <repository>
    <id>clojars.orgid>
    <url>http://clojars.org/repourl>
  repository>
repositories>

<build>


Add the swank-clojure dependency

This will allow to start a swank server from within the Web app.
Add to your pom.xml:
   
   
   <dependency>
     <groupId>swank-clojuregroupId>
     <artifactId>swank-clojureartifactId>
     <version>1.4.2version>
   dependency>
   
dependencies>


Create the ServletContextListener that will launch Swank

Create the class: ./src/main/java/cljinject/SwankServletContextListener.java:
package cljinject;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import clojure.lang.Compiler;
import java.io.StringReader;

public class SwankServletContextListener implements ServletContextListener{

    // keep a hand on the context so we can get it from within clojure
    public static ServletContext context;

    public void contextInitialized(ServletContextEvent contextEvent) {
        context = contextEvent.getServletContext();

        final String startSwankScript =
        "(ns my-app\n" +
        "  (:use [swank.swank :as swank]))\n" +
        "(swank/start-repl) ";

        // launch swank in a separate thread otherwise it will 
        // block the webapp startup
        new Thread() {
            public void run() {
                try {
                    Compiler.load(new StringReader(startSwankScript));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
    }

    public void contextDestroyed(ServletContextEvent contextEvent) {
    }
}


Declare the ServletContextListener

In web.xml:
       <url-pattern>/cometd/*url-pattern>
   filter-mapping>
   
   <listener>
     <listener-class>
       cljinject.SwankServletContextListener
     listener-class>
   listener>
   
web-app>


Launch the webapp

Now in the Jetty logs you should see:
my-app=> Connection opened on null port 4005.
nil


Connect from Emacs

Note: You may need to install slime-rep.
  • In emacs: M-x slime-connect
  • Now in the slime REPL type:
user> (.println System/out "---- hello from clojure!!! -----")
nil
  • You should see it on the Jetty console:
---- hello from clojure!!! -----


Mess around ;-)

We took care to expose the context in the SwankServletContextListener, so now we can access it from the REPL and mess around:
user> cljinject.SwankServletContextListener/context
#<SContext ServletContext@178820c{/cljinject,file:}>

That's it!
Isn't life beautiful?
HTML generated by org-mode 6.33x in emacs 23

jeudi 12 novembre 2009

Using gwt-dispatch without GWT RPC


I watched the Best Practices For Architecting Your GWT App video, and followed the excellent GWT MVP Example tutorial.

And it gave my some ideas on how to implement the command pattern in my GWT application.

The pattern is nice in a GWT app:
  • We have a centralized component to handle cross-cutting concerns like caching, logging, handling network errors, etc.
  • The components are no longer aware of the implementation details of the client / server communication, so:
    • Better unit testing: Handlers can be easily mocked
    • Handlers implementation could be swapped with minimal impact to:
      • change the client / server communication: For example change JSON to GWT RPC
      • or why not while the application is running: For example to implement an offline mode, the JSON handlers would be swapped to Gears handlers, without the components noticing.

I wanted to use the gwt-dispatch lib, which implements this pattern in GWT, problem is: At the time of this writing, in gwt-dispatch, handlers could only be implemented on the server and with GWT RPC.
And in my application the client / server communication is done with SOAP.

So I hacked a couple of classes to handle the commands on the client side:
  • RequestBuilderDispatcher, a implementation of DispatchAsync, capable of executing RequestBuilderActionHandlers, 2 public methods:
    • addHandler : To add a RequestBuilderHandler for a specific Action
    • execute: To execute an Action with a RequestBuilderActionHandler.
  • RequestBuilderActionHandler : All handlers must implements this interface.  2 methods are defined:
    • getRequestBuilder: Prepare and configure a RequestBuilder with the content of the Action: Setup the url, post method, request parameters, ...
    • extractResult: Extract a Result from the server Response.

RequestBuilderActionHandler.java

package fr.hrgwt.client.command;

 

import net.customware.gwt.dispatch.shared.Action;

import net.customware.gwt.dispatch.shared.Result;

 

import com.google.gwt.http.client.RequestBuilder;

import com.google.gwt.http.client.Response;

 

public interface RequestBuilderActionHandler<A extends Action<R>, R extends Result> {

 

              /**

              * Prepare a RequestBuilder.

              */

              RequestBuilder getRequestBuilder(A action);

 

              /**

              * Extract the result from the response.

              */

              R extractResult(Response response);

 

              Class<A> getActionType();

}


Here an example of implementation:

FindAllCheckListXmlActionHandler.java

package fr.hrgwt.client.command.impl; 


import com.google.gwt.http.client.RequestBuilder;

import com.google.gwt.http.client.Response;

import fr.hrgwt.client.command.RequestBuilderActionHandler;

 

public class FindAllCheckListXmlActionHandler

                            implements

                            RequestBuilderActionHandler<FindAllCheckListAction, FindAllCheckListActionResult> {

 

              @Override

              public Class<FindAllCheckListAction> getActionType() {

                            return FindAllCheckListAction.class;

              }

 

              @Override

              public RequestBuilder getRequestBuilder(FindAllCheckListAction action) {

                            return new RequestBuilder(RequestBuilder.GET, "/myurl");

              }

 

              @Override

              public FindAllCheckListActionResult extractResult(Response response) {

                            // TODO extract the xml from the response here

                            return null;

              }

}


Code for RequestBuilderDispatcher:

RequestBuilderDispatcher.java

package fr.hrgwt.client.command;

 

import java.util.HashMap;

import java.util.Map;

 

import net.customware.gwt.dispatch.client.DispatchAsync;

import net.customware.gwt.dispatch.shared.Action;

import net.customware.gwt.dispatch.shared.Result;

 

import com.google.gwt.http.client.Request;

import com.google.gwt.http.client.RequestBuilder;

import com.google.gwt.http.client.RequestCallback;

import com.google.gwt.http.client.RequestException;

import com.google.gwt.http.client.Response;

import com.google.gwt.user.client.rpc.AsyncCallback;

 

/**

* Implements DispatchAsync with a RequestBuilder.

*/

public class RequestBuilderDispatcher implements DispatchAsync {

              @SuppressWarnings("unchecked")

              Map<Class<Action>, RequestBuilderActionHandler> handlersMap = new HashMap<Class<Action>, RequestBuilderActionHandler>();

 

              @SuppressWarnings("unchecked")

              public <A extends Action<R>, R extends Result> void execute(A action,

                                          final AsyncCallback<R> asyncCallback) {

                            Class<? extends Action> actionType = action.getClass();

                            final RequestBuilderActionHandler<A, R> handler = handlersMap

                                                        .get(actionType);

                            if (handler == null) {

                                          throw new IllegalArgumentException("unregistered actionType:"

                                                                      + actionType);

                            }

                            RequestBuilder requestBuilder = handler.getRequestBuilder(action);

                            requestBuilder

                                                        .setCallback(createRequestCallback(asyncCallback, handler));

                            try {

                                          requestBuilder.send();

                            }

                            catch (RequestException e) {

                                          throw new RequestRuntimeException(e);

                            }

              }

 

              // visibility package for tests

              <A extends Action<R>, R extends Result> RequestCallback createRequestCallback(

                                          final AsyncCallback<R> asynchCallback,

                                          final RequestBuilderActionHandler<A, R> handler) {

 

                            return new RequestCallback() {

 

                                          @Override

                                          public void onResponseReceived(Request request, Response response) {

                                                        asynchCallback.onSuccess(handler.extractResult(response));

                                          }

 

                                          @Override

                                          public void onError(Request request, Throwable exception) {

                                                        throw new RuntimeException("not implemented yet");

                                          }

                            };

              }

 

              @SuppressWarnings("unchecked")

              public <A extends Action<R>, R extends Result> void addHandler(

                                          RequestBuilderActionHandler<A, R> handler) {

                            handlersMap.put((Class<Action>) handler.getActionType(), handler);

              }

}



Now in the initialization of the app:
  • Create a dispatcher that will be injected in the components that needs it (manually or better with GIN)
  • Register an ActionHandler

                            RequestBuilderDispatcher dispatcher = new RequestBuilderDispatcher();

                            dispatcher.addHandler(new FindAllCheckListXmlActionHandler());


Nothing special when using the dispatcher (the client code won't know anything about the implementation, it could be GWT RPC) :

              @Override

              protected void onBind() {

                            dispatcher.execute(new FindAllCheckListAction(),

                                                        new AsyncCallback<FindAllCheckListActionResult>() {

 

                                                                      @Override

                                                                      public void onSuccess(FindAllCheckListActionResult result) {

                                                                                    display.setCheckLists(result.getCheckLists());

                                                                      }

 

                                                                      @Override

                                                                      public void onFailure(Throwable caught) {

                                                                                    throw new RuntimeException("not implemented yet");

                                                                      }

                                                        });

Conclusion

The good

  • Quick implementation of an ActionHandler on the client side.

The bad

  • Rollback is not handled
  • No GIN integration

Remarks

  • My build is dependant on the gwt-dispatch library, this is not really necessary as I am only using 3 interfaces from it (Action, Result and AsyncDispatch). It would be interessting to see if there's an impact on the size of the compiled Javascript modules.

Membres

Qui êtes-vous ?