Angel \”Java\” Lopez on Blog

May 13, 2013

Domain-Specific Languages: Links, News And Resources (3)

Filed under: Domain-Specific Languages, Links, Programming Languages — ajlopez @ 10:58 am

Previous Post

Domain-Specific Languages, implemented in different languages.

dsl – Mini-languages in Python – Stack Overflow
http://stackoverflow.com/questions/1547782/mini-languages-in-python

Creating Domain Specific Languages in Python
http://www.slideshare.net/Siddhi/creating-domain-specific-languages-in-python

Building Your Own Java, Part 2
http://www.infoq.com/presentations/JetBrains-MPS-DSL-2
Alex Shatalin and Václav Pech continue their language building demo using JetBrains MPS started in Part 1 of this presentations (see “Building Your Own Java, Part 1” on InfoQ).

DSLs in Clojure
http://www.infoq.com/presentations/DSL-Clojure

Building Your Own Java, Part 1
http://www.infoq.com/presentations/JetBrains-MPS-DSL
Alex Shatalin and Václav Pech hold a hands on demonstration on using JetBrains MPS to generate a new language, including version control, debugging, testing, refactoring, etc.

Mission: Impossible–Purely Declarative User Interface Modeling
http://www.infoq.com/presentations/S4-Declarative-DSL-UI

A DSL for Scripting Refactoring in Erlang
http://www.infoq.com/presentations/Wrangler-Refactoring-Erlang

Webr-DNQ – Web Application Development with Pleasure
http://www.infoq.com/presentations/Webr-DNQ
Maxim Mazin and Evgenii Schepotiev discuss the advantages of using DSLs by exemplifying application development with JetBrains MPS (Meta Programming System) and the Webr-DNQ framework.

Emulating "self types" using Java Generics to simplify fluent API implementation | Passion For Code
http://passion.forco.de/content/emulating-self-types-using-java-generics-simplify-fluent-api-implementation

dlitvakb/deklarativna
https://github.com/dlitvakb/deklarativna
A Declarative HTML DSL for Ruby

clojure @ runa :: dynamic pricing through DSLs
http://www.infoq.com/presentations/clojure-runa-dynamic-pricing-through-DSLs
Domain Model – Reference Guide 4.0 – Mendix Community Platform
https://world.mendix.com/display/refguide4/Domain+Model

Petter’s Random Thoughts on Software: DSL’s, UIX and Agile Development, Lessons Learned
http://pettergraff.blogspot.it/2012/05/overview-over-last-8-months-ive-been.html

cgrand/parsley
https://github.com/cgrand/parsley
A DSL for creating total and truly incremental parsers in Clojure

InfoQ: How to Integrate Models And Code
http://www.infoq.com/articles/combining-model-and-code

My Links
http://delicious.com/ajlopez/dsl

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

May 11, 2013

Express: Links, News And Resources (3)

Filed under: Express, JavaScript, Links, NodeJs, Web Development — ajlopez @ 10:45 am

Previous Post

A third entry with links about Express, the “standard” Node.js web framework.

Simple Screenshot
https://github.com/visionmedia/screenshot-app
simple screenshot application & web service powered by Express, Redis, node-canvas, palette, and PhantomJS.

Khelldar/Angular-Express-Train-Seed · GitHub
https://github.com/Khelldar/Angular-Express-Train-Seed
A starting point for making an AngularJS app with node.js on the back end, using the Express Train framework

Modular web applications with Node.js and Express on Vimeo
http://vimeo.com/56166857
This short screencast describes how you can use Express’ app mounting feature to create modular self-contained applications to construct your product.
By @tjholowaychuk, Express author

node-money – Cloud9
https://c9.io/renatoargh/node-money
Sample app with access control

Structuring a node.js web application with Express | Gama & Ferraz
http://zeppelin-ci.org/structuring-a-node-js-web-application-with-express/
Explain node-money example

thinkphp/express-basic · GitHub
https://github.com/thinkphp/express-basic
A simple Website on Node.js with Express, Jade and Stylus deploying on Heroku

jesusabdullah/node-ecstatic · GitHub
https://github.com/jesusabdullah/node-ecstatic
A simple static file server middleware that works with both Express and Flatiron

node-home-automation – Node.js based home automation server application – Google Project Hosting
http://code.google.com/p/node-home-automation/

astalker/nblog · GitHub
https://github.com/astalker/nblog
A Simple CMS module for Node Js using Express, EJS and Mongo

genem
https://github.com/madhums/node-genem
A MVC generator for node.js (uses express, mongoose, jade and passport.js)

How an Event Loop works « Matt’s Hacking Blog
http://baudehlo.wordpress.com/2013/02/14/how-an-event-loop-works/

Cross-domain AJAX, Express.js and Access-Control-Allow-Origin – /var/blog – John Roepke – Boston Area Web and Open Source Software Developer
http://john.sh/blog/2011/6/30/cross-domain-ajax-expressjs-and-access-control-allow-origin.html

anddimario/mucontent · GitHub
https://github.com/anddimario/mucontent
MuContent – CMS based on ExpressJs for create multisite, multilanguage and modular web application with Node.Js

mdalpi/battleship-node · GitHub
https://github.com/mdalpi/battleship-node
Battleship Game with chat support written in Node.JS

smurthas/gdata-js · GitHub
https://github.com/smurthas/gdata-js
Simple Google Data API client for OAuth 2.0

agrueneberg/Corser · GitHub
https://github.com/agrueneberg/Corser
A highly configurable, middleware compatible implementation of CORS for Node.js.

express.js middleware to support CORS pre-flight requests
https://gist.github.com/2344435

jawerty/Node2Blog · GitHub
https://github.com/jawerty/node2blog
A simple and easy to setup node.js blog template. For the casual blogger

http – Extracting POST data with Express – Stack Overflow
http://stackoverflow.com/questions/11002046/extracting-post-data-with-express/14125262#14125262

express.io – realtime-web framework for nodejs
http://express-io.org/

My Links
http://delicious.com/ajlopez/express

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

May 10, 2013

TDD Kata (4): Lawnmover

Previous Post

In the previous post, I commented about by experience at pre-round at Google Code Jam.

The exercise B was Lawnmover:

https://code.google.com/codejam/contest/2270488/dashboard#s=p1

Problem

Alice and Bob have a lawn in front of their house, shaped like an N metre by M metre rectangle. Each year, they try to cut the lawn in some interesting pattern. They used to do their cutting with shears, which was very time-consuming; but now they have a new automatic lawnmower with multiple settings, and they want to try it out.

The new lawnmower has a height setting – you can set it to any height h between 1 and 100 millimetres, and it will cut all the grass higher than h it encounters to height h. You run it by entering the lawn at any part of the edge of the lawn; then the lawnmower goes in a straight line, perpendicular to the edge of the lawn it entered, cutting grass in a swath 1m wide, until it exits the lawn on the other side. The lawnmower’s height can be set only when it is not on the lawn.

Alice and Bob have a number of various patterns of grass that they could have on their lawn. For each of those, they want to know whether it’s possible to cut the grass into this pattern with their new lawnmower. Each pattern is described by specifying the height of the grass on each 1m x 1m square of the lawn.

The grass is initially 100mm high on the whole lawn.

I solved it, see:

https://github.com/ajlopez/TddOnTheRocks/tree/master/Lawnmover

As usual, the commit history by test:

https://github.com/ajlopez/TddOnTheRocks/commits/master/Lawnmover

I could solve the first small set provided by Google. But I failed with the big set, because my algorithm was not efficient enough. The big set should be solved in 8 minutes, and if you cannot, there is no other chance. My initial algorithm (see comments) attacked the largest number in cells. My second algorithm switched to start with the minimal numbers (my first guess was that both algorithms had the same time, but I was wrong). I learnt: some problems in Google are hard to test by hand, we don’t have the use case (input and expected output), that is the main difficult.

More katas are comming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

May 8, 2013

TDD Kata (3): Tic-Tac-Toe-Tomek

Previous Post
Next Post

Two weeks ago, I participated of the pre round of Google Code Jam. Exercise A was TicTacToeTomek:

https://code.google.com/codejam/contest/2270488/dashboard

Problem

Tic-Tac-Toe-Tomek is a game played on a 4 x 4 square board. The board starts empty, except that a single ‘T’ symbol may appear in one of the 16 squares. There are two players: X and O. They take turns to make moves, with X starting. In each move a player puts her symbol in one of the empty squares. Player X’s symbol is ‘X’, and player O’s symbol is ‘O’.

After a player’s move, if there is a row, column or a diagonal containing 4 of that player’s symbols, or containing 3 of her symbols and the ‘T’ symbol, she wins and the game ends. Otherwise the game continues with the other player’s move. If all of the fields are filled with symbols and nobody won, the game ends in a draw. See the sample input for examples of various winning positions.

Given a 4 x 4 board description containing ‘X’, ‘O’, ‘T’ and ‘.’ characters (where ‘.’ represents an empty square), describing the current state of a game, determine the status of the Tic-Tac-Toe-Tomek game going on. The statuses to choose from are:

  • “X won” (the game is over, and X won)
  • “O won” (the game is over, and O won)
  • “Draw” (the game is over, and it ended in a draw)
  • “Game has not completed” (the game is not over yet)

If there are empty cells, and the game is not over, you should output “Game has not completed”, even if the outcome of the game is inevitable.

An input file can be downloaded with different board positions, and our program should generate an output file with the results: X won, O won, tie, or the game is not finished, yet.

I wrote my solution using TDD, you can see the result at:

https://github.com/ajlopez/TddOnTheRocks/tree/master/TicTacToeTomek

The commit history, with test granularity:

https://github.com/ajlopez/TddOnTheRocks/commits/master/TicTacToeTomek

It was a simple exercise, and well adapted to TDD. Google accepted my solution to a small input file, and to a big one too. I should write about the other exercises (B, C, D) that are a bit more complicated for TDD:

- Each problem should be solved quickly. With TDD, you could implement an algorithm but it could be not efficient.

- The algorithm to implement is not evident, and you should write the increasing difficult input cases.

- Sometimes, given an input state, it is hard to reach (even by hand) a right output solution. Many of my attempts were rejected by Google, without much info about what is the right solution, so you must review manually each result.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

May 6, 2013

TDD Kata (2): Alien Language

Previous Post
Next Post

Some week ago, Google Code Jam was mentioned in Spanish list TDDev.  One of the  past problems of this contest was Alien Language.

After years of study, scientists at Google Labs have discovered an alien language transmitted from a faraway planet. The alien language is very unique in that every word consists of exactly L lowercase letters. Also, there are exactly D words in this language.

Once the dictionary of all the words in the alien language was built, the next breakthrough was to discover that the aliens have been transmitting messages to Earth for the past decade. Unfortunately, these signals are weakened due to the distance between our two planets and some of the words may be misinterpreted. In order to help them decipher these messages, the scientists have asked you to devise an algorithm that will determine the number of possible interpretations for a given pattern.

A pattern consists of exactly L tokens. Each token is either a single lowercase letter (the scientists are very sure that this is the letter) or a group of unique lowercase letters surrounded by parenthesis ( and ). For example: (ab)d(dc) means the first letter is either a or b, the second letter is definitely d and the last letter is either d or c. Therefore, the pattern (ab)d(dc) can stand for either one of these 4 possibilities: add, adc, bdd, bdc.

I liked the problem. See in the page that we should read an input file with the words and patterns to process. We can download input files from the problem page, and upload an output file with our solution, generated by our problem. Then, Google will return if the answer is correct or not. So, I wrote a solution using  TDD:

https://github.com/ajlopez/TddOnTheRocks/tree/master/AlienLanguage

You can read commit history, with test granularity, at:

https://github.com/ajlopez/TddOnTheRocks/commits/master/AlienLanguage

One of the latests things I did was to refactor the detection of words that match a pattern. I could improve it, maybe using a word tree instead of a list of words, as I did in SimpleBoggle.

At the end, I wrote a console program that accepts an input file and writes an output file, as Google contest requires. I downloaded a big input file from Google, processed it, and uploaded the solution. Google answered: OK:

TDD rules ;-)

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

May 5, 2013

Mass Programming Language (3) Commands

Filed under: .NET, C Sharp, Mass, Open Source Projects, Programming Languages — ajlopez @ 6:16 pm

Previous Post

Today let’s review command implementation in Mass (see repo). In the class library project, I have a dedicated namespace and folder for commands:

There are commands for if, while, for, for each, etc… Every command implements the ICommand interface:

public interface ICommand
{
    object Execute(Context context);
}

See that is very similar to IExpression. But I wanted to keep a separation between commands and expressions, at least for this first implementation, in order to have a clear separation of basis concerns.

A typical example of command is WhileCommand, partial code:

public class WhileCommand : ICommand
{
    private static int hashcode = typeof(WhileCommand).GetHashCode();

    private IExpression condition;
    private ICommand command;

    public WhileCommand(IExpression condition, ICommand command)
    {
        this.condition = condition;
        this.command = command;
    }

    public object Execute(Context context)
    {
        for (object value = this.condition.Evaluate(context); 
            value != null && !false.Equals(value);
            value = this.condition.Evaluate(context))
        {
            this.command.Execute(context);
            if (context.HasContinue())
                context.ClearContinue();
            if (context.HasBreak())
            {
                context.ClearBreak();
                break;
            }
        }

        return null;
    }
}

In Mass, every null or false value is false. All other value is true. I should refactor the code to have a central method IsFalse to be invoked in the above While code and in other commands, like IfCommand.

Another sample of command is ForEachCommand, partial code:

public class ForEachCommand : ICommand
{
    private string name;
    private IExpression expression;
    private ICommand command;

    public ForEachCommand(string name, IExpression expression, ICommand command)
    {
        this.name = name;
        this.expression = expression;
        this.command = command;
    }

    public object Execute(Context context)
    {
        var values = (IEnumerable)this.expression.Evaluate(context);

        foreach (var value in values)
        {
            context.Set(this.name, value);
            this.command.Execute(context);
            if (context.HasContinue())
                context.ClearContinue();
            if (context.HasBreak())
            {
                context.ClearBreak();
                break;
            }
        }

        return null;
    }
}

See that for Mass every IEnumerable value can be used as the element provider for ForCommand. I added some methods to the current context to signal the present of a break or continue (in the current version, I added return treatment, too).

And, as usual, all this code was developed using TDD flow: you can read repo commit history.

Next posts: Lexer, Parser, Mass samples, Mass scripting, using Mass from our .NET programs.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

May 3, 2013

New Month’s Resolutions: May 2013

Filed under: NodeJs, Open Source Projects — ajlopez @ 4:18 pm

Review of my April’s resolutions:

- Update Mass [complete] see repo
- Start NodeAima [complete] see repo
- Give a one-day course on Node.js [complete]
- Update AjGenesis [pending]
- Update AjGenesisRuby [pending]
- Update SimpleGo [pending]
- Update RubySharp [complete] see repo 
- Update ClojSharp [pending]

Additionally, I worked on:

- Update AjFabriqNode [complete] see repo
- Update NodeSamples [complete] see repo (see Distributed Fractal)
- Update SimpleStorm [complete] see repo
- Update SimpleBus [complete] see repo
- Update SimpleBroadcast [complete] see repo
- Update SimpleGA [complete] see repo

All this work is related to a talk I gave one week ago, about Distributed Applications and Node.js

May’s resolutions:

- Update Mass
- Update RubySharp
- Give a talk, Intro to Ruby
- Update AjGenesis
- Update ClojSharp
- New posts about Mass
- New posts about Distributed Applications and Node.js

More fun and work.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

April 30, 2013

Mass Programming Language (2) First Expressions

Filed under: .NET, C Sharp, Mass, Open Source Projects, Programming Languages — ajlopez @ 9:31 am

Previous Post
Next Post

Before using Mass language in samples (see repo), I want to visit some implementation points. First, a news: now there is a solution (at (en https://github.com/ajlopez/Mass/blob/master/Src/Mass.sln) that can be compiled with Visual Studio C# Express.

The Mass solution has a class library project. There is a namespace dedicated to expressions:

An expression implements IExpression:

  
public interface IExpression
{
	object Evaluate(Context context);
}

A Context keeps a key/value dictionary, to save the current variables:

  
public void Set(string name, object value)
{
	this.values[name] = value;
}

public object Get(string name)
{
	if (this.values.ContainsKey(name))
		return this.values[name];

	if (this.parent != null)
		return this.parent.Get(name);

	return null;
}

(notice that it supports nested context: each context can have a parent).

A simple expression is ConstantExpression, that returns a constant, without using the received context. A constant is any .NET value/object:

  
public class ConstantExpression : IExpression
{
	// ...

	private object value;

	public ConstantExpression(object value)
	{
		this.value = value;
	}

	public object Evaluate(Context context)
	{
		return this.value;
	}

	// ...
}

Another expression is the one that evaluates a variable name in the current context:

  
public class NameExpression : IExpression
{
	// ...

	private string name;

	public NameExpression(string name)
	{
		this.name = name;
	}

	public object Evaluate(Context context)
	{
		return context.Get(this.name);
	}

	// ...
}

The context is important: it could be the context of the current function, of a closure, of current object, of current module, etc… The same name could refer defers differente associated variables, as in other programming languages.

As usual, all these classes (expressions, Context, …) were written using the flow of TDD. You can check the test project and the repo commits history were there is evidence of that flow.

Next posts: some additional expressions, commands, using Mass for scripting, using Mass from our .NET programs.

Kee tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

April 26, 2013

TDD Kata (1): Rock Paper Scissors Lizard Spock

Two weeks ago, I read at Spanish list TDDev a new kata published at the blog Aprendiendo TDD:

Piedra Papel Tijera Lagarto Spock

based on a problem published in (Spanish post)

http://www.solveet.com/exercises/Kata-Piedra-Papel-Tijera-Lagarto-Spock/20

I took the description from Wikipedia article:

http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock

The rules of Rock-paper-scissors-lizard-Spock are:

  • Scissors cut paper
  • Paper covers rock
  • Rock crushes lizard
  • Lizard poisons Spock
  • Spock smashes (or melts) scissors
  • Scissors decapitate lizard
  • Lizard eats paper
  • Paper disproves Spock
  • Spock vaporizes rock
  • Rock breaks scissors

And then, I started to code the solution using TDD, in C#. You can check re result at:

https://github.com/ajlopez/TddOnTheRocks/tree/master/SpockGame

The commit history reveals commit by test:

https://github.com/ajlopez/TddOnTheRocks/commits/master/SpockGame

See the first test/commit: it didn’t compile. Then, it started to compile, but with red result. Then, I added the minimal code to pass the test, and refactor, and so on.

I decided to have two tests, one per permutation: testing Scissors cut Paper, and other testing Paper is cut by Scissors. I could refactor the test to have an internal method testing in both ways

The initial design was based on:

- Having an instance of Game class (the alternative was to have static methots, directly in the class)

- Having an enumeration for game options (Play.Scissors, etc…)

- Having an enumeration for the play result (PlayResult.Tie, PlayResult.FirstPlayer…)

Instead of having play result, I could put a method that compare two options, deciding which one is “greater”. Today, I could refactor the implementation to use that approach.

See the last refactor: I could leave the code as is, with if command deciding which play wins, to decide when the first player wins:

But I wrote a  new way:

based on Wikipedia article suggestion:

One way to remember the rules is to remember the standard "rock-paper-scissors" ordering, where each gesture defeats the one before it, and is defeated by the one after. But then add the two novel gestures near the word they approximately rhyme with:

  1. Rock
  2. Spock
  3. Paper
  4. Lizard
  5. Scissors

In this expanded list, each gesture is defeated by the following two options, and defeats the preceding two.

But I feel the previous code is more clear. Sometimes, we must decide between having a clear code vs a clever one.

More TDD katas are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

April 25, 2013

Mass Programming Language (1) Inception

Filed under: .NET, C Sharp, Mass, Open Source Projects, Programming Languages — ajlopez @ 9:09 am

Next Post

Three weeks ago, I was working on the implementation of an interpreted language, written in C#. The new language is called Mass (dedicated to  @MArtinSaliaS):

https://github.com/ajlopez/Mass

The current solution has three projects: a class library, its tests, and a console program, mass.exe, that launches Mass programs

You can run a hello.ms:

mass hello.ms

The classic Hello world source code:

println("Hello, world")

An example with classes and objects

class Person
	define initialize(firstname, lastname)
		self.firstname = firstname
		self.lastname = lastname
	end
	
	define getName()
		return self.lastname + ", " + self.firstname
	end
end

adam = new Person("Adam", "TheFirst")

println(adam.getName())

An example with access to .NET types and objects:

dirinfo = new System.IO.DirectoryInfo(".")

for fileinfo in dirinfo.GetFiles()
	println(fileinfo.Name)
end

The idea is  to have a dynamic language that leverages an underlying language provided with a rich class library and ecosystem, like in AjSharp and other of my projects. Before Mass, I was working on:

- Implementing Python in C# (see PythonSharp)

- Implementing Ruby in C# (see RubySharp)

- AjSharp (see repo and post)

But this time I wanted to implement something with simple sintax and semantic. Indeed, I was playing with “simple” ideas for a compiler over Javascript, see SimpleScript (1) First Ideas.

Then, with Mass, I deliberately wanted to avoid:

- Multiple commands in the same line (I discarded ‘;’ like in Ruby)

- Syntax based in spaces and indentation (Python discarded)

- Function invocation using only the name; Mass impose the explicit use of parenthesis (Ruby discarded; Mass is like JavaScript)

- Base values and classes (integers, strings, lists, etc…) having a crowd of methods (like Ruby and Python). No, Mass prefers to expose and use the underlying language/class library.

Then, I wanted:

- Functional values, as first-class citizens, like in JavaScript. So, having to put explicit parenthesis to invoke a function allows me to use the name of the function as a functional value

- Dynamic objects: each object can be extended at any moment, with new instance variables, object functions, a la JavaScript

- Syntax based in lines: each command has its own line. No command separation

- Syntax based in keywords: the end of a command list is marked with ‘end’, no braces

- As far as possible, only one way to do something, instead of the many ways motto a la Perl

- Complete keywords, then ‘define’ instead of ‘def’

- Simple inheritance at classes. But Mass could be expressive without written classes, using native classes from .NET framework and other libraries. It could be used as an scripting language.

- Explicit setting of variables that are out of the local scope (a topic for next posts)

- Variable scope by file, like in the require of JavaScript/NodeJs/CommonJS

- Module by file, with a require that automatically searches in directories, a la NodeJs/CommonJs. Notably, Mass can consume node_modules folder, so Mass module can be published and installed using NPM!

- Package manager, using NPM. You can use package.json to declare the dependencies, and publish new modules at NPM (using ‘mass-‘ as the suggested namespace).

In upcoming posts, I will write more details about implementation, guiding design ideas, examples. But now, you can see the code and the test examples at public repo. And yes, all was written by baby steps, using TDD.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 28 other followers