segunda-feira, 15 de junho de 2015

Package-require: require a library, eventually loading the package from the Emacs package archives

package-require is an Emacs Lisp utility function that will install a package if not installed from the archives, and then load the corresponding library. If the library name differs from the package name, it can be supplied.

(defun package-require (package-name &optional library-name)
  "Install the package named PACKAGE-NAME from the repositories
  if it doesn't exist locally and then load the library given by
  LIBRARY-NAME, or PACKAGE-NAME if it is homonimous.  Both names
  are strings, not symbols."

  (let ((package (intern package-name)))
    (unless (package-installed-p package)
      (package-install package)))
  (load-library (or library-name package-name)))

To use it, write in your emacs file, for instance:

(package-require "bpe")

What if the package name differs from the library to load, like in AucTeX? Just write the library name after the package. The following example loads "tex-site", installing "auctex" first if it does not exist.

(package-require "auctex" "tex-site")

A shell script to redo the home .cabal directory

Haskell user installation: automation with an interface

Note: A new version was posted at the 16 Jun 2015.  Please use the download link below, as it has been updated.

Haskell is a powerful language that you will love to hate and hate yourself to death by loving it. Haskell is expressive and, in my experience, will teach you more and more about computation as you use it. Like python, opens a new way to think of computing architecture and algorithms.
One of the most interesting tools of Haskell is The Haskell Cabal. Cabal is a system for building and packaging Haskell libraries and programs. There is a tool, cabal-install, which retrieves programs and libraries from source repositories, builds them on the local machine, and installs them by default in the user's home directory. It also allows sandboxes, directories whose library setup differs from the user or from the system libraries, used mainly for development.

Shell to the rescue

Since cabal is not a package manager, after a while you will find that it is more fruitful to just wipe the whole user installed packages and start over. It usually meant for me remembering all the packages I use and install them by hand. I have made before a shell script to help me automate that task. It worked very well, but I failed always to remember all the command line arguments I had to pass to install certain sections.
The following script is a bash script that will wipe out the ~/.cabal and ~/.ghc directories (with the exception of the configuration files) and restart the installation. Running this shell script allows an user to fire it and forget until it is built. It is nothing sophisticated, nor it needs to be. It just does the job.

Download

Link for download: haskell.

Requirements

It uses the Bourne Again Shell (bash), and has some code specific to bash. You should have it installed on your machine (all Linux distributions have bash, and most use it by default).
You should also have a working installation of Haskell in your computer, with the Cabal development libraries and the cabal command line tool.

Usage

Just follow the menus. You can wipe the whole cabal installation (.cabal and .ghc). This script always preserve the configuration files.
As for the main menu:

  • Clean wipes the cabal installation.
  • Install wipes the previous installations and installs only cabal.
  • All reinstalls all package blocks, unattended. Fire it up and go on a date. It'll be ready when it is ready.
  • All other items install some package blocks.

What if I want different packages?

Edit any of the functions beginning by install_, adapting them to your needs. If you want a new block, add it to the main menu, and create a corresponding do_ function, taking the existing ones as example.

Licence

Public domain.
If you wish to suggest improvements, feel free to add them to the comment box, and I'll open a git repository in github.

quinta-feira, 19 de março de 2015

How to modify an ember component from a controller.

The Problem

How do I change state in an ember component from an ember controller? For instance, calling a method or setting a variable?

The solution

The simple way is to share a property between the controller and the component. That is the gist of two-way binding, after all! What we may do is to use the binding facilities in Ember.

At the controller:

App.MyRouteController = Ember.Controller.extend({
    myComponent1Var: false;
    myComponent2Var: false;

    (...)
});

We have defined two property for two different instances of MyOwnComponent. At the component we will now pass the property at the controller as a binding for a component property

At the route template:

{{my-own-component varBinding="controller.myComponent1Var}}

(...)

{{my-own-component varBinding="controller.myComponent2Var}}

At this point, two instances of MyOwnComponent share completely different variables. Now, each of the components shares it's own property with the controller, and the property is called var (from varBinding). The component knows nothing about the controller and the controller knows nothing about the component. They just share state.

But what if I want to call a method at the component from the controller? Just watch the common property at the component. Add this to the component:

App.MyOwnComponent = Ember.Component.extend({
    (...)

    varChanged: function() {
        if (this.get('var')) {
            this.method();
        }
    }.observes('var');

    (...)
});

At the varChanged method, the method named method is called whenever the property var changes into a truish value.

The two-way binding allows one to communicate from a controller to a component ª(and vice-versa) without any of these objects having to ke aware of the other.

quinta-feira, 11 de dezembro de 2014

How to have an automatic timestamp update.

The problem

One SQL table has two fields to record the rime of creation and of the last modification. Can the database update these fields automatically when the record is created and updates?

The solution

The table is assumed to have the fields:

CREATE TABLE Users (
  ...,
  created_at DATETIME NOT NULL DEFAULT NOW(),
  modified_at DATETIME,
  ...
);

We have resolved the creation date problem already. Upon creation, created_at will be filled in with the creation date by default, unless another date is passed in.

Now, how can the database update automatically the modified_at field when the field is modified? With an SQL Trigger. If the RDBMS supports triggers, the problem will be solved with code as following:

CREATE TRIGGER TrgUsers_updateTimestamp
  AFTER UPDATE ON Users
    FOR EACH ROW
       SET NEW.modified_at = NOW();

A simple and elegant solution, and thus the applications connecting to the database will not have to worry with timestamps. After any update on any table row, the modified_at field is updated to the current time. This trigger also supports multi-row updates.

segunda-feira, 31 de março de 2014

Singleton pattern in C++, using templates.

The singleton pattern names a programming structure used to replace global variables, without any of their downsizes. A plethora of implementation suggestions have been produced in the previous years. Most are needlessly complicated.

I am posting here a simple and effcient implementation of the singleon pattern. Using function templates and static variables, to get a reference to a singleton instance is no more than getting back a C++ reference. This implementation adds one line to each class that is to be enabled as a singleton, and no inheritance. That is quite useul, since inheritance usually means looking up virtual tables and following them.

First part: the instance function.

instance should return a reference to the given class. C++ Templates come to our help. C++ templates are like C prerocessor macros: they are evaluated at compile time. Thus, they add no overhead whatsoever during the execution of the program.

The function is the following:

template<class T>
inline T &instance() {
  static T instance;
  return instance;
}

That's it: it creates and returns a reference of an instance of the object. That reference is only created once, upon the first invocation of this function. The instance lives wth the application, and is automatically dereferenced before quitting the application. Thus, the destructor is properly called. Any invocation of the function for a given class will return the same instance of that class.

As the function is inlined, a good compiler should take that hint and limit the generated code to a simple return of the reference address.

Second part: the class.

We have a function that retuns us an instance of the class, but we are the to adapt the class to use the function. We need to lock the class against unwanted instantiations. Both the constructor and the destructor should be private or protected. And as we do it, we shuld say that instance<MyClass<> is a friend of the class.

class Game {
public:

  void run() {};

  friend Game &(instance<Game>)();

private:
  Game() {};
  ~Game() {};
};

By making the constructor and the destructor protected, we invalidate any instantiations of the class thet does not come from any friend functions or classes. As the only friend function that we allow to instatiate objects is our template function, we are sure that only through our instance retriever an object of such class can be held.

So that's it, no inheritance and no pesky virtual tables or map dereferences.

Making life easier

One can now get a reference of the global object and run a method there by saying:

  instance<Game>().run();

That is prone to errors and tedious to write, is it not?

What about defining a function to retrieve our code? An inline function takes no more time to execute than a preprocessor macro, and still allows us type checking.

inline Game &
the_game() {
  return instance<Game>();
}

Now we may invoke the run method with:

the_game().run();

You may opt to go one step further and emulate a global variable, without parenthesis:

#define the_game (instance<Game>())

And the invocation will be as simple as:

the_game.run();

I still use the parenthesis.



Comments are, of course, appreciated.

quinta-feira, 16 de janeiro de 2014

A Timer object with angular.js

The problem

Angular JS is probably the best javascript framework around. Simple things are simple and complicated things are possible. As with any other framework in any language, one has to adapt the thought patterns around the intricacies and the peculiarities of the language and the library. One has to take time to learn Angular, but once it is finally understood, the productivity is enhanced.

I have done some web pages with angular. For one I wanted a timer object that I coud stop, start, set the period and the method at will. For instance, within a controller or a directive or any other Angular object:

var timer = new Timer(5000, myFunction, $timeout).start()

This will start the timer and run myFunction every five seconds.

timer.delay(3);

This function will delay the firing of the timer for 3 periods (in the case, 15 seconds.

The rest of the functions should be obvious.

The implementation

The code should be simple to just copy and paste. It uses the $timeout global object from Angular, som make sure angular.js is imported into the page.

var Timer = function(period, meth, $timeout) {
  var tID = null;
  var tPeriod = period || 5000;
  var tDelay = 0;
  var tMeth = meth || null;


  function delay(periods) {
    tDelay = periods;
    return this;
  }

  function setPeriod(period) {
    tPeriod = period || 5000;
    return this;
  }

  function setMethod(meth) {
    tMeth = meth || null;
    return this;
  }

  function stop () {
    if (typeof(tID) != null) {
      $timeout.cancel(tID);
      tID = null;
    }
    return this;
  }

  function start() {
    tID = $timeout(function () {
       if (tDelay) {
         tDelay -= 1;
       } else {
         if (tMeth) {
           tMeth();
         }
       }
       start();
    }, tPeriod);
    return this;
  }

  function restart() {
    stop();
    start();
    return this;
  }

  return {
    'delay': delay,
    'restart': restart,
    'setMethod': setMethod,
    'setPeriod': setPeriod,
    'start': start,
    'stop': stop
  }
}

As always, suggestions are appreciated.

terça-feira, 7 de janeiro de 2014

Emacs - purge session files

The problem

I have always been bothered with the session files left by emacs is user-emacs-directory, normally ~/.emacs.d/. These files have the name session.[a long string of hexadecimal characters] and save the session variables when emacs exits without being explicitely terminated. Like when one ends up the session by the session manager and does not bother to close the emacs window first.

After a few days, a set of session files ends up cluttering the emacs directory. These files lose their purpose once one does not want to restore the session on the next emacs invocation, but they are not purged automatically.

The solution

purge-session-files deletes all session files, preserving the n most recent. n defaults to 1. The function can be called interactively. In such case, the user is given the choice of the number of session files to preserve (defaulting to one).

Here is the code:

(defun purge-session-files (&optional n)
  "Purge all session files but the n more recent files."
  (interactive (list (read-number "Number of files to preserve" 1)))
  (let ((files (directory-files user-emacs-directory t "session.*")))
    (dolist (file (butlast files (or n 1)))
      (delete-file file nil))))