Angular2

I have being playing around with Angular2 for last couple of months.

Here is my list of links on Angular2 that helped me in my journey:

Functional Reactive Programming(FRP) in Angualr2

 

EMACS 25.1 + SLIME on Windows 10

Here is my Lisp Development Environment setup on Windows 10:

  1. Clozure Lisp http://ccl.clozure.com/
    Unzip the Windows Zip ftp://ftp.clozure.com/pub/release/1.11/ccl-1.11-windows.zip
    Add the Lisp path to PATH variable.
  2. EMACS 25.1
    Unzip the Windows 64 binaries emacs-25.1-x86_64-w64-mingw32.zip and run bin/runemacs.exe
  3. QuickLisp
    Download the QuickLisp lisp files https://beta.quicklisp.org/quicklisp.lisp
    Run

    wx86cl64.exe -load <path to quicklisp.lisp>
  4. SLIME
    Open your emacs configuration file in EmacsCTRL+X CTRL+F -then-> ~/.emacsThen insert following entries to enable MELPA repository

    (when (>= emacs-major-version 24)
     (require 'package)
     (add-to-list
     'package-archives
     '("melpa" . "http://melpa.org/packages/")
     t)
     (package-initialize))

    Now restart Emacs. After restart type  ALT+X and type

    package-install RET slime

    Then set following values in Emacs configuration file (“~/.emacs”)

    ;;; Lisp - SLIME
    
    (setq inferior-lisp-program "C:/ccl-1.11-windows/wx86cl64.exe")
    
    (setq slime-contribs '(slime-fancy))

    Now on restart of Emacs, when I type CTRL+X slime I get following SLIME prompt

screenshot-13

Enjoying Lisp + Emacs

Learning Lisp

Yesterday, I happen to read a comic based Lisp tutorial at www.lisperati.com. It was fun to go through the tutorial which very easily introduces to Lisp and creates a Text-based adventure game in Lisp.

After playing the game, I build up my first Emacs Lisp function to restart the game.

 

Restart function in Emacs Lisp

(defun restart ()
        (progn
         (setq object-locations
           (remove-if (lambda (x)
             (eq 'body (second x)))
              object-locations))
         (look)))

Explanations:
On line two I have used progn function, that takes a list of forms to execute and returns the result of last form execution. In this function, I have two forms, first one to clear from object-locations the user inventory i.e. items picked in the play. The second form starts the game with look function

To reset user inventory, I have used remove-if function to clear from object-locations list all items that belongs to user body and then set the result list back to object-locations. Even though this is not pure Functional programming, it is step towards it as instead of modifying the existing list, a list is created by filtering and assigned as new object-locations list.

Happy Lisping.

Emacs – 101

I have recently developed interest in learning Emacs editor. I have been learning Functional Programming languages like Haskell and lately Erlang and was looking for Editor/IDE for them. IntelliJ Idea have plugins for these languages but the IDE is very heavy. So came to Emacs and am learning it. Particularly like the idea that every thing can be done with keyboard shortcut so no need to move hands between mouse and keyboards.

A bit of warning for faint hearts, don’t try emacs as quick learning. It has steep learning curve.

I have started with basic navigation commands like (these are for WINDOWS) :

CTRL+c CTRL+f : Open a file

Move in file :

CTRL+f : move forward one character (RIGHT key)

CTRL+b : move back one character (LEFT key)

CTRL+n : move down on next line (DOWN key)

CTRL+p : move up on previous line (UP key)

CTRL+a : Move to the beginning of the lines (Home key)

CTRL+e : Move to the end of the lines (End key)

ALT+f : Move forward one word

ALT+b : Move backward one word

Other navigation:

ALT+r : Moves to center most line of window

ALT+< : Move to top of the buffer

ALT+> : Move to end of the buffer

CTRL+v : PageDown key

ALT+v : PageUp key

 

The other good feature is Org-mode. For beginners found the tutorial at http://orgmode.org/worg/org-tutorials/org4beginners.html

What is Org-mode?

From the website orgmode.org :

“Org mode is for keeping notes, maintaining TODO lists, planning projects, and authoring documents with a fast and effective plain-text system.”

The  Org-Babel model can be use to write Literate Programming Documents.

More to come…

 

Haskell OpenCL on Windows

To try running OpenCL bindings in Haskell (https://github.com/HIPERFIT/hopencl) I had installed Intel SDK for OpenCL (https://software.intel.com/en-us/intel-opencl) on Windows 8.1 64 bit machine.

To install hopencl, the instructions is :

cabal install c2hs
cabal install

The first command to install c2hs succeeded.
The second command to install hopencl failed with :

Resolving dependencies...
In order, the following will be installed:
hopencl-0.2.1 (reinstall)
Configuring hopencl-0.2.1...
Failed to install hopencl-0.2.1
Build log ( C:\Users\...\AppData\Roaming\cabal\logs\hopencl-0.2.1.log ):
Configuring hopencl-0.2.1...
setup.exe: Missing dependency on a foreign library:
* Missing C library: OpenCL
This problem can usually be solved by installing the system package that
provides this library (you may need the "-dev" version). If the library is
already installed but in a non-standard location then you can use the flags
--extra-include-dirs= and --extra-lib-dirs= to specify where it is.

To make it compile sepcify the OpenCL include and lib like :

C:\>cabal install --ext
ra-include-dirs="c:\Program Files (x86)\Intel\OpenCL SDK\include" --extra-lib-di
rs="c:\Program Files (x86)\Intel\OpenCL SDK\lib\x64"

AngularJs scripts and minification

AngularJS provides Dependency Injection where a controller, service or module can expect Angular to pass the dependencies.

For e.g. if we have two services and a controller then controller can get the service dependency by writing the formal parameter in it’s constructor with the same name as service name.

var myModule = angular.module('simpleApp',[]);
myModule.service('dataService',function($http){
	this.getData = function() {
		return $http.get('/some/url');
	}

});
myModule.controller('simpleController',function($scope, dataService){
	dataService.getData().then(function(data){
		$scope.data = data;
	});
});

In the code above, simpleController is getting the dataService dependency because the parameter is also name as dataService. If the name is something else Angular will not be able to fulfill the dependency.

JavaScript Minification

With JavaScript minification the same JavaScript code will look like this

var myModule=angular.module(&quot;simpleApp&quot;,[]);

myModule.service(&quot;dataService&quot;,function(e){this.getData=function(){return e.get(&quot;/some/url&quot;)}});

myModule.controller(&quot;simpleController&quot;,function(e,t){t.getData().then(function(t){e.data=t})})

Due to minification the parameters have been renamed to a smaller length name like ‘e’, ‘t’. As now the service parameter name in simpleController is ‘t’ AngularJS will not be able to fulfill the dependency.

Dependency Injection with JavaScript minification

To enable DI we have to write controller and service methods with an array whose elements are list of all parameter names in string followed by the function.

var myModule = angular.module('simpleApp',[]);
myModule.service('dataService',[ '$http', function($http){
	this.getData = function() {
		return $http.get('/some/url');
	}

}]);
myModule.controller('simpleController',['$scope', 'dataService', function($scope, dataService){
	dataService.getData().then(function(data){
		$scope.data = data;
	});
}]);

And the code post minificaiton

var myModule=angular.module('simpleApp',[]);

myModule.service('dataService',['$http',function(e){this.getData=function(){return e.get('/some/url')}}]);

myModule.controller('simpleController',['$scope','dataService',function(e,t){t.getData().then(function(t){e.data=t})}])

Note the strings are not getting changed so now AngularJS will pass ‘dataService’ to parameter

‘t’ in the above minified code.

Alternatively, if you are not using module constructor and service calls then you can set $inject as array of parameter names.

var myModule = angular.module('simpleApp',[]);
function dataService($http){
this.getData = function() {
  console.log('called getData');
		return  'done';
	};
};
dataService.$inject = ['$http'];
myModule.service('dataService', dataService);
	
 function simpleController($scope, dataService){
	$scope.msg = 'loading'; 
   
     $scope.msg = dataService.getData();
	  
 }
 simpleController.$inject = ['$scope','dataService'];
 
 myModule.controller('simpleController',simpleController);

RemoteDataSource in Upshot.js

RemoteDataSource in Upshot.js can be used to fetch and save data using DataProvider.

Let’s see it’s constructor.

RemoteDataSource takes an options object as single parameter.

The options can have following parameters:

1. bufferChanges: (Optional) If ‘true’, edits to model data are buffered until RemoteDataSource.commitChanges.  Otherwise, edits are committed to the server immediately.
            
2. result:
(Optional) The observable array into which the RemoteDataSource will load model data.
       
3. dataContext:
(Optional) A DataContext instance that acts as a shared cache for multiple DataSource instances.  When not supplied, a DataContext instance is instantiated for this RemoteDataSource.
       
4. entityType:
The type of model data that will be loaded by this RemoteDataSource instance.
       
5. provider:
(Optional) Specifies the DataProvider that will be used to get model data and commit edits to the model data.  Defaults to upshot.DataProvider which works with System.Web.Http.Data.DataController.
       
6. providerParameters:
(Optional) Parameters that are supplied to the DataProvider for this RemoteDataSource and used by the DataProvider when it gets model data from the server.
       
7. mapping:
(Optional) A function (typically a constructor) used to translate raw model data loaded via the DataProvider into model data that will be surfaced by this RemoteDataSource.
       

RemoteDataSource have four public methods:

1. setSort : Establishes the sort specification that is to be applied as part of a server query when loading model data.

Parameter: sort (required)

Should be supplied as an object of the form { property: <propertyName> [, descending: <bool> ] } or an array of ordered objects of this form.
 
When supplied as null or undefined, the sort specification for this RemoteDataSource is cleared.

2. setFilter : Establishes the filter specification that is to be applied as part of a server query when loading model data.

Parameter: filter (required)

Should be supplied as an object of the form { property: <propertyName>, value: <propertyValue> [, operator: <operator> ] } or an array of ordered objects of this form.
 
When supplied as null or undefined, the filter specification for this RemoteDataSource is cleared.

3. refresh: Initiates an asynchronous get to load model data matching the query established with setSort, setFilter and setPaging.

Parameters:

  1. options (optional) : There are no valid options recognized by RemoteDataSource.
  2. success (optional) : A success callback with signature function(entities, totalCount).
  3. error(optional): An error callback with signature function(httpStatus, errorText, context).

OData access using jsonp

The upshot.js ver. 1.0 does not support jsonp calls. To enable jsonp I have modified the DataProvider.OData get method enable jsonp callback like this.

var jsonpCall ;
            if (parameters) {
                operation = parameters.operationName;
                operationParameters = parameters.operationParameters;
                jsonpCall = parameters.jsonpCall ? (parameters.jsonpCall === true): false;
            }
            if(jsonpCall){
              OData.defaultHttpClient.enableJsonpCallback = true;
             }

Using odata provider access Netflix OData :

(function () {
    var Netflix = window.Netflix = window.Netflix || {};

    Netflix.Movie = function (properties) {
        var self = this;

        self.Name = properties.Name;
        self.ShortName = properties.ShortName;
        self.ShortSynopsis = properties.ShortSynopsis;
        self.AverageRating = properties.AverageRating;
        self.ReleaseYear = properties.ReleaseYear;
        self.Runtime = properties.Runtime;

    }
    Netflix.Movie.Type = "Title:#Netflix.Catalog.v2"

    Netflix.CourseViewModel = function (options) {
        var self = this;

        var dataprovider = new upshot.ODataDataProvider();
        var courseDataSourceParameters = {
            provider: dataprovider,
            providerParameters: { url: options.serviceUrl, dataType: 'jsonp', operationName: "Titles", operationParameters: { "$top": "10"}, jsonpCall : true },            
            entityType: Netflix.Movie.Type,
            bufferChanges: true
        };
        var courseDataSource = new upshot.RemoteDataSource(courseDataSourceParameters);
        self.Titles = [];
        courseDataSource.refresh({}, function (entities, totalCount) {
            self.Titles = [];
            $.each(entities, function (index, item) {
                var entity = new Netflix.Movie(item);
                self.Titles.push(entity);
            });

            alert("Total movies loaded " + self.Titles.length);
        });

    }

})();