Showing posts with label development. Show all posts
Showing posts with label development. Show all posts

Monday, January 04, 2016

TypeScript and NodeJS, I'm sold

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript, the way you expect it to be.
I’ve heard of it a long time ago, but recently with TypeScript 1.7 it got async functions, which means you can awaitasynchronous function calls, similarly to C#, Vala, Go and other languages with syntax support for concurrency. That makes coroutines a pleasant experience compared to plain JavaScript. That’s also the main reason why I didn’t choose Dart.
I’m writing a NodeJS application so I decided to give it a go. Here’s my personal tour of TypeScript and why I’m sold to using it.

Does it complain when using undeclared variables?

console.log(foo);
Cannot find name 'foo'.
Sold!

Does it infer types?

var foo = 123;
foo = "bar";
Type 'string' is not assignable to type 'number'.
Sold!

Does it support async arrow functions?

async function foo() {
}
var bar = async () => { await (foo); };
Sold!

Does it support sum types?

var foo: number | string;
foo = 123;
foo = "bar";
Sold!

Does it play nice with CommonJS/AMD imports and external libraries?

Yes, it does very well. Sold!

Is it easy to migrate from and to JavaScript?

Yes. TypeScript makes use of latest ECMAScript features in its syntax when possible, so that JavaScript -> TypeScript is as painless as possible. Sold!
Also to go back from TypeScript to JavaScript, either use the generated code, or remove all the type annotations in the code by yourself.

Does it have non-nullable variables?

No. This is mostly due to the JavaScript nature though. But I’m sure the TypeScript community will come up with a nice solution throughout this topic.

I’m going to use TypeScript wherever I can in this new year instead of plain JavaScript. In particular, I’m rewriting my latest NodeJS application in TypeScript right now.
I hope it will be a great year for this language. The project is exceptionally active, and I hope to contribute back to it.

Saturday, April 06, 2013

Build Vala applications with Shake build system

I'm going to introduce you a very nice alternative to make: the Shake build system, by setting up a builder for your Vala application project.

First of all, you need to know that Shake is a library written in Haskell, and it's meant to be a better replacement for make. Let's start by installing cabal and then shake:
apt-get install cabal-install
cabal update
cabal install shake

TL;DR; this is the final Build.hs file:
#!/usr/bin/env runhaskell
import Development.Shake
import Development.Shake.FilePath
import Development.Shake.Sys
import Control.Applicative hiding ((*>))

app = "bestValaApp"
sources = words "file1.vala file2.vala file3.vala"
packages = words "gtk+-3.0 glib-2.0 gobject-2.0"

cc = "cc"
valac = "valac"
pkgconfig = "pkg-config"

-- derived
csources = map (flip replaceExtension ".c") sources
cobjects = map (flip replaceExtension ".o") csources

main = shakeArgs shakeOptions $ do
  want [app]
  app *> \out -> do
    need cobjects
    pkgconfigflags <- pkgConfig $ ["--libs"] ++ packages
    sys cc "-fPIC -o" [out] pkgconfigflags cobjects
  cobjects **> \out -> do
    let cfile = replaceExtension out ".c"
    need [cfile]
    pkgconfigflags <- pkgConfig $ ["--cflags"] ++ packages
    sys cc "-ggdb -fPIC -c -o" [out, cfile] pkgconfigflags
  csources *>> \_ -> do
    let valapkgflags = prependEach "--pkg" packages
    need sources
    sys valac "-C -g" valapkgflags sources
    
-- utilities
prependEach x = foldr (\y a -> x:y:a) []
pkgConfig args = (words . fst) <$> (systemOutput pkgconfig args)

Just tweak app, sources and packages to match your needs, chmod +x Build.hs then run ./Build.hs .

Explanation.
The words function splits a string by spaces to get a list of strings, e.g. ["file1.vala", "file2.vala", "file3.vala"].

The csources variable maps .vala file names to .c file names. Same goes for cobjects. It's the equivalent of $(subst .vala,.c,$(SOURCES)) you'd do with make.

There it comes the main. The shakeArgs shakeOptions part will run shake with default options. Shake provides handy command line options similar to make, run ./Build.hs -h for help.

The want [app] tells shake we want to build the app object by default. That's equivalent to the usual first make rule all: $(APP).

Then we define how to build the executable app with app *> \out -> do. We tell shake the dependencies with need cobjects. This is similar to $(APP): $(COBJECTS) in make but not equivalent. In shake dependencies are not static like in many other build systems. This is one of the most interesting shake features.
The rest is quite straightforward to understand.

Then we define how to build each .o object with cobjects **> \out -> do. Here the out variable contains the actual .o required to be built, equivalent to $@ in make. Then we need [cfile], in order to simulate %.o: %.c like in make.

One more feature shake has out-of-the-box that make doesn't is how to generate more files from a single command. With make you'd use a .stamp file due to valac generating several .c files out of .vala files. Then use the .stamp as dependency.
With shake instead we consistently define how to build .c files with csources *>> \_ -> do, then shake will do the rest.

The shake project is very active. You can read this tutorial to learn Haskell basics, and the reference docs of shake. The author homepage has links to cool presentations of the shake build system.

Thursday, December 06, 2012

Refactory.org is down

Unfortunately many of my snippets in this blog have been written and uploaded exclusively on refactory.org . It was a free service for uploading snippets of any kind, with a friendly versioning system and other cool features.
It's now inactive since several months. I'm sorry for anybody stumbling upon any post that has code hosted at refactory.org . From now on I will try to put the code in the post itself whenever I can, or find better places to upload the code.

Thursday, November 22, 2012

Grab focus on Gtk Widget

Many times I had to give focus to a newly created Gtk widget that still had to be mapped to screen. Since widget.grab_focus() does not work if the widget is not displayed on the screen, then I always used an idle source to delay the operation.
Today I noticed that the idle may be too late: if the user is writing something, then some key strokes may be lost because the idle runs slightly after the widget has been mapped. You may think that's imperceptible to the user, but that's not true in some cases.

So I've tried connecting to the map, map-event and show signals (also "after"), without success: the handler is called slightly before the right time thus grab_focus() will not work.

Then I ended up with this working solution, that will grab the focus as soon as the widget is first drawn to the screen:

void focus_widget (Widget widget) {
  // it may be already displayed
  widget.grab_focus ();
  // grab focus right after the widget is drawn
  // for the first time
  ulong sigid = 0;
  sigid = widget.draw.connect (() => {
    widget.grab_focus ();
    widget.disconnect (sigid);
    return false;
  });
}

I still don't know exactly what's the best way to grab focus as soon as the widget can really grab it. So if you have any better idea, please let me know :-)

Thursday, September 08, 2011

Vala language introduction on IRC

Hi,
I've lately held an talk on IRC about the Vala programming language for the Ubuntu App Developer Week. I've introduced the basics of the Vala language and its features.
You can read the log of the talk here.

Saturday, July 09, 2011

Python/Ruby like generators in Vala

Hello,
the post below is copied straight from here.

Here I'll show a cool snippet code making use Vala async functions and iterators for emulating Python/Ruby generators. Creating a generator is as simple as extending the Generator class and implementing the generate() method.

abstract class Generator {
    private bool consumed;
    private G value;
    private SourceFunc callback;

    public Generator () {
        helper ();
    }

    private async void helper () {
        yield generate ();
        consumed = true;
    }

    protected abstract async void generate ();

    protected async void feed (G value) {
        this.value = value;
        this.callback = feed.callback;
        yield;
    }

    public bool next () {
        return !consumed;
    }

    public G get () {
        var result = value;
        callback ();
        return result;
    }

    public Generator<G> iterator () {
        return this;
    }
}

class IntGenerator : Generator<int> {
    protected override async void generate () {
        for (int i=0; i < 10; i++) {
            yield feed (i);
        }
    }
}

void main () {
    var gen = new IntGenerator ();
    foreach (var i in gen) {
        message ("%d", i);
    }
}

You can find the above code snippet here as well.

Tuesday, July 05, 2011

Why I'm still using Emacs

Hello,
I'm using emacs since a long time by now. Everytime I ask myself why I'm using it, given emacs certainly isn't the easiest environment for programming. So, I often tried to replace emacs with other IDEs or editors, using several extensions and so on, but I still miss these killer features in a single editor:
  • Pressing a key (whatever it is, TAB in emacs) correctly/smartly indent the row according to the current language.
  • Split view, horizontal and vertical
  • No horizontal scrollbar, rather wrap the text
  • Opening/closing files without either opening a dialog or using the mouse
  • Search, search and replace (also with regexp variant) without opening any dialog
  • Switching between buffers using the longest-common-subsequence matching, without using the mouse (i.e. I don't care about file tabs, but about switching among them fast)
  • Indent entire code regions
  • Vala, C, Python, Java, Shell, Autoconf/Automake, Make and Javascript support

So, I'm not using emacs because I love it, but because it's actually the only editor with the above features.

What I'm looking for? I'm looking for a new editor/IDE, less complex, easier to customize, having the above features plus smart completion and symbol browser.
Emacs can have completion and symbol browser as well, but managing those buffers such as speedbar suck a little, things get complicated to use and to customize.

If anybody knows of such an editor, please let me know :)

Thursday, June 02, 2011

Writing binary files with bash

Hello,
I'm trying to see if I'm able to write some binary file using bash. So, when writing a binary file you often want to write a number into binary format. I ended up with this simple function for writing numbers in little endian:

function num2bin() {
printf $(printf %.$(($2*2))x\\n $1|
sed 's/\([0-9a-f][0-9a-f]\)/\\x\1/g')|
awk -F '' '{ printf $4$3$2$1 }'
}


The first parameter is the number to write, the second is the number of bytes (up to 4). For example "num2bin 40 4" will output a 4-byte long string containing the number 40 in little endian.

How do we use it? I wrote an example script for creating a wav file with noise (according to wav specifications) that you can read here.

Let me know if you have a simpler version of the num2bin function.

Sunday, May 22, 2011

Enforce facebook chat through SSL

Hello,

since a few days facebook is supporting SSL for the chat. The problem is that it can't be enabled.

Until facebook enables this you can use the SSLGuard plugin for firefox, which enforces SSL for a list of web sites, including all facebook pages and the chat as well.

We have some good ideas for sslguard that we'd like to get in for the next releases... stay tuned.

Saturday, May 14, 2011

Valag 1.2 released

Hello,
I've just released the 1.2 version of Valag, the graph generator for analyzing Vala code trees. Only relevant change is the fact that it now builds against libvala-0.14.

More information and download at the Valag homepage.

Friday, January 14, 2011

Base64 and Quoted-Printable GConverters for GMua

Hello,
lately I'm writing GMua for educational purposes and for evaluating Vala, whose purpose is to simplify writing Mail User Agents or simple scripts, ala Java Mail.
It currently parses IMAP (not yet complete) and has a graphical interface called Gutt (yes, inspired by Mutt) for testing.
In order to parse MIME parts with base64 or quopri content-transfer-encoding I chose to implement a couple of GConverter (will use GMime a day, maybe when they switch to gio, not yet needed) in Vala that you can find here:
I'm pretty sure there are bugs in these converters, by the way I wanted to share them :)

Sunday, December 19, 2010

Valag 1.1 released, graph generator for the Vala AST

Hello,
a new version of Valag, a graphviz generator for the Vala language AST, has been released.

Changes since 1.0 version:
  • Add --format and --prefix options.
  • Update to latest libvala-0.12.
  • Bug fixes.
This new version also distributes the xdot.py program as a viewer for the generated graphs.

More information and download at the Valag homepage.

Friday, December 17, 2010

Maja - The Vala to Javascript compiler

Hello,
I've just released the first version of Maja, the Vala to Javascript compiler. The mapping is not quite complete but you can do pretty much everything you could do with javascript directly. There are (still incomplete) bindings for the qooxdoo framework and the demo browser is being ported to vala successfully.
Maja can be used in any environments, not only web browsers.
Programming in Vala saves you from lots of type safety troubles (Javascript), lot of typing (Java) and the syntax is really enjoyable as it is quite close to the Javascript model.

Usage and download at the homepage.

Thursday, July 29, 2010

Using Mash with Vala

Hello,
recently Mash has been released. It is a library for reading models in PLY format and creating Clutter actors from them. For reference, Blender is able to export to PLY. It means you can draw your models with Blender and use Clutter as rendering engine.
Clutter is a 3D canvas and animation toolkit while Blender is a 3D modelling suite.

What I've tested so far is porting the Monkey Viewer C example to Vala: code snippet and monkey PLY here.



That is going to be awesome, stay tuned!

Friday, June 18, 2010

Idea duplicated again

Hello,
I'd like to point you to this firefox extension HTTPS Everywhere (June 17th, 2010) and SSLGuard which is also a firefox extension (first released Oct 14th, 2009).

The code of the former extension is a lot more complicated and the result is not always quite the same as SSLGuard. In fact, while they support secure cookies and per-website custom rules, SSLGuard lets you add custom websites to be secured directly from a friendly graphical dialog.

You could even install both of them, apparently they don't conflict.

It's the second time decrew ideas are being duplicated. This happened sometimes ago with SSLtoHTML (ettercap plugin) and sslstrip (standalone application), but they released the code before us. Funny isn't it?

I'm not complaining about anything (I'm not saying "copy", I say "duplicate"), just clearing things out. Of course, better have more choice and more works.

Friday, April 02, 2010

Valagtkdoc 1.0

Hello,
yes... this is the nth program I'm writing in this period. I hope this is the last one :)

Valagtkdoc is a tool that integrates Vala with GTK-Doc for documentation generation.

You can find download and example usage at the homepage.

I think it's far from being perfect, and actually I haven't tried integrating it with autotools, but it shouldn't be that hard. Unfortunately, you have to somehow break the gtk-doc rule "do not run it manually" because valagtkdoc goes in the middle between gtkdoc-scan and gtkdoc-mkdb.

If anybody has a better solution, please tell me :)

Sunday, March 14, 2010

Vala and Graphviz

Hello,
it's often useful for Vala hackers to have a graphical representation of the code tree and control flow blocks. Therefore I've created a simple application called Valag which generates four types of diagrams using Graphviz for each state of the Vala compiler.

This is the first release, there're many things to fix and enhance (like command line options) but it is working quite good already to give support when hacking Vala.

Homepage, screenshots and download here.

Wednesday, March 03, 2010

Debian/GNOME bug triage ended

Hello,
I'm writing about the work done in the bug triage weekend of the Debian/GNOME team, started at 27th Feb and ended in 28th Feb.
The result is great, 167 bugs have been closed and many more have been triaged and forwarded upstream.

Thanks to everybody who contributed, especially to whom has done it for the first time (well, you can still continue working on the remaining bugs ;) ).

Thursday, February 04, 2010

Vala 0.7.10 released

Hello,
I'm lately following the Vala development and finally we got a new release with plenty of bug fixes and enhancements which makes Vala even more interesting and usable as general purpose language.

Here's the announcement.
I'd like to point you to the new Vala journal, a good resource to stay tuned with Vala changes periodically.

News:
* Support coalescing operator ??.
* Support to_string and bitwise complement with enums.
* Return handler id when connecting signal handlers.
* Support struct comparison.
* Support constructor chaining in structs.
* Enforce protected member restrictions.
* Improve performance of flow analysis.
* Support automatic line continuations in Genie.
* Improvements to the .gir reader and writer.
* Add --enable-mem-profiler commandline option.
* Many bug fixes and binding updates.

Friday, November 27, 2009

Mimaggia, cairo tester

Hello,
From GNOME

I've created a simple pygtk project for testing cairo statements. It includes a sort of terminal where you write statements in a simple language. It features immediate preview of what you write.

Say it's a new format for images.
If you want to test it and see the code, ask me.