Saturday, May 28, 2016

Creating a simple babel compiler command line

As a continuation of the previous post, we can create a npm executable to compile our script which makes more sense. :)

You can clone the code from here.  Please follow the installation instruction.

For this task, we will be creating a custom babel plug-in.

The main code resides in bin/hsc.js which uses node to open a file and pass to babel for further transformation. At line 11, we have a plugin keyword and we pass in our helloscript. This is how we tell babel to use our newly created plugin.




If you look at helloscript.js it uses babel specification to traverse and locate a variable called 'a' and then attempt to convert it to ''total''.

For our purpose, it resides in 'path,parent.id.name'. This is basically discovered via trial and error as I traced through the AST output.



If you have problem zooming down on an expression, try to do a console.log(path), and slowly narrow down your PATH by adding more element to the constraint for example, PATH.PARENT. (path's parent object).


Most importantly, you need to understand different tree expression like BinaryExpression, MemberExpression and Identifier. More info can be found here.







Creating your babel transpiler



Babel helps to convert ES2015 and Jsx to javascript. So it is a javascript to javascript - parser and code generator.

In this tutorial i will show you a very simple tutorial working with babel main components namely :

a) babylon - a parse which takes javascript code and convert into AST.

b) babel-traverse - allow us to traverse through AST

c) babel-generator - code generator


Our goal is to convert this code

let  a = 2 + 2

to

let total = 2 + 2

Simple enough, so lets get started.

1. First we need to create a new folder.

2. Issue npm init and provide relevant information here

3. npm install --save babylon
    npm install --save babel-generator


4. Create a file called index.js and it should contain the following codes :-



Type node index.js to run this example

You will see the output :

{ map: null, code: 'let total = 2 + 2;' }

Noticed that we have converted "a" to total.

To really understand how things tied together please read babel handbook.

Entire code can be download here.


Tabu search



Tabu search is a combinatorial optimization problem whereby it tries to look for the best possible solution to a problem such as travelling salesman problem.

When a best move is found it is added into a tabu. List of tabu is used to ensure search path / node is not traverse again. Tabu is remove with each iteration and only when it reaches zero, then search moves forward.

This is to prevent search process to get stuck locally.

For example, please take a look at diagram below. We have 5 location labeled (0, 1, 2, 3, 4) and each has an associated cost. Tabu search is able to tell us minimum cost associated with our chosen path.




We use a 5x5 (2d) matrix to keep track of the cost associated with a edge / path / link.

C# code for this TSP tabu search can be download here. Also included in the code is hill climbing algorithm for solving tsp problem.

The output looks like this

Search done! 
Best Solution cost found = 9
Best Solution :
0 1 2 4 3 0 








Monday, May 23, 2016

Distributing your npm package as an executable

Here are simple steps to setup your first npm package. You do not need to publish directly to npm repository instead you can push to git.
First thing you gotta do is - setup github.

a) Create a new repository and clone it to your local drive

b) Execute 'npm init'.

c) We will also use index.js as the default entry point. This means  we will create a file called "index.js" and it will host our modules, which might looks something like this. (Please note : You will need to add 

#! /usr/bin/env node 

as shown below, otherwise node will not be available. :-



d) Next, we need to edit our package.json and add the following


"preferGlobal": false,
"bin": {  "npmcalc": "./bin/index.js"

This additional properties basically tells node that we are going to get an executable called npmcalc and source located in a file called index.js under bin folder.

If you set 'preferGlobal' : true - you need to install npmcalc with a -g option, otherwise you might not be able to find the npmcalc itself.



It would look something as follows :-




e) Please git commit your code and push to master branch.

git commit

git push origin master


f) Next, lets try out by installing it from github.

npm install git://github.com/appcoreopc/npmcalc.git


g) From the command line, execute

npmcalc 10 10

Total result = 20





Sunday, May 22, 2016

Publishing your own npm package to github



Here are simple steps to setup your first npm package. You do not need to publish directly to npm repository instead you can push to git.
First thing you gotta do is - setup github.

a) Create a new repository and clone it to your local drive

b) Execute 'npm init'.

c) We will also use index.js as the default entry point. This means  we will create a file called "index.js" and it will host our modules, which might looks something like this :-



It just provide function to call and execute hello.

d) Commit our code changes with git and then issue the following command to make master as the default branch in git.

git push origin master

e) Next, create any new folder and issue the following command to see if we can install our package correctly.

npm install git://github.com/appcoreopc/hellonpm.git

f) To verify, type the following on node command line.

node

and then let's call our library into action with the follow codes.

var a  = require('hellonpm').hello;
a('jeremy')


If you wanna push to npm, first you gotta have an account and pay them some money. The command to upload is really easy :-

npm publish





Monday, May 16, 2016

Setup Typescript and React for your project with typings support


I know many might be asking about this, here's a quick guide for you to do it.


1. Issue the following command af

npm init

npm install -g typescript typings webpack

npm install --save react react-dom


// allowing interoperability between typescript and webpack

npm install --save-dev ts-loader source-map-loader


npm link typescript


// get typings files for working with react. Warning this might give you error so used steps below - using tsd instead

typings install --ambient --save react
typings install --ambient --save react-dom


--ambients tells typings to grab from DefinitelyTyped

The command above was failing when i was working with it, so i used tsd. So go ahead and install tsd.

npm install -g tsd

Get react typings with the following command

tsd install react

tsd install react-dom 


2. Add your tsconfig.json typescript configuration as follows :-




3. Create your first component using code as follow, please name it Hello.tsx (.tsx is an typescript supported file extension for react)




4. Create your index.tsx which will render your components to the right dom object




5. Next we are going to create index.html and we can see our react compoent in action.



6. Configure our webpack by creating webpack.config.jsfile.

7. We done, run webpack from the command line and open index.html to see our react/typescript component integration. 


Phew!! Here a github project for this.













Setting up typescript in visual studio





Create a typical Asp.Net 5 MVC applications. Vs2015 provide an excellent tool to work with typscript.

a)  Create a file called package.json and use npm to load the required dependencies.

b) Setup gulpfile.js

c) Run gulp from Task Runner.

1.  Creating package json 

Then you need to create file called package.json






Package json should contains the followings contents :

"devDependencies": {
    "typescript": "^1.5",
    "gulp": "^3.9.0",
    "gulp-typescript": "^2.8.0",
    "merge": "^1.2.0"
  }

2  Creating gulp file  Goto Add->New Item->Client-> Gulp configuration as shown below :-




After you added it, your gulp file should look like something below :-



The thing to note here is that your ts file will be compiled into a .js file and placed in a folder called 'script' (as shown in line 12).
,
3. Start your task runner by press Ctrl + Alt + Backspace or goto View->Other Windows -> Task Runner Explorer.

4. You can create any typescript file and put it under a folder called 'Typescript/definition'. Any file placed here will be compiled into .js by Typescript.

A simple typescript might looks this.














Saturday, May 14, 2016

Javascript generator - iterator - or did i completed miss the idea out.


Nice .... good to know javascript supports iterator with a function * (asterisk).

let index;

// declares our iterator function which returns number from i to 9

const generatorFunction = function* ()
{
    for (var i=0; i < 10; i++)
    {
        yield i;
    }
};

////////////////////////////////////////////////////////////////////v
// logs out output
////////////////////////////////////////////////////////////////////v

for (index of generatorFunction ()) {
    console.log(index);
}

output will be something like

0
1
2
3
4
5
6
7
8
9

Recapping my work signalR ....




Working with signalR is really straigth forward, all you need to do is create your "Hub".

Lets go configure your MVC project with the following command :-




Next, lets get some concepts out the door. In signalR what we write eventually gets 'callable' by clients. One way of thinking about it is, public methods here is what client call.

Whenever you call  this.Client.CLIENT_METHOD_TO_INVOKE (normally in hubs) you are invoking client side javascript function.



Create a hub, as such and you're ready to test your SignalR apps.

Step 1 :-



At this point you would like to test out your code, by going to http://localhost:YOUR_PORT/SignalR/hubs and you will see javascripts rendered on your browser and your method is reflected here also.



Somehow i have added some server side calls but it is not reflected here. :)


Step 2 :-

Modify your index.html and you're ready to go.




So we start our hub (subscribe to a specific hub if you will) and then directly under it, we have javascript code that send message to server perfHub.server.send and invokes client's side function with perfHub.client.subscribeMessage .

We can easily differentiate between calls to either server and client as it is stated clearly in the method call.


For a more advance example, please take a look at the following source.