Wikipedia

Search results

16 August 2015

git add openshift remote

Step 1:
Find your Openshift app ssh via
$ rhc apps
and copy the Git url corresponding to the application of interest

Step 2:
You can then add that ssh value as a remote, named as openshift below
$ git remote add openshift -f "$SSH"

15 August 2015

MQTT broker with HTTP bridge

For those looking to develop a driver, bridge, or thin abstraction layer between their devices and services: all is right with the world.

Definitely check out, and brush up, on your Node.js-fu because it makes developing (i.e. prototyping and/or full scalable solutions) absolutely possible. This tidbit won't get in to the nitty gritty of how to maximize Node.js for multicore, however, those resources are available in the API documentation as well as other blog posts floating around the internets.

Here, I'll demonstrate a simple and effective way to utilize the Mosca framework alongside the Node.js http module to get dual MQTT:HTTP citizenship.

If you're interested to develop your own MQTT broker, and in Javascript, then look no further than Mosca. It's MQTT 3.1.1 compliant, and works with amazingly high fidelity; and in other words, it's quality stuff. Both Mosca and Node.js modules function via C++, and are pretty close to the metal. The abstraction provides plenty of bang for the buck.

Additionally, the npm dispatch module was used to provide some pretty useful routing capability. Here, the code is in single file mode: what you'd want to do is to call this server.js file from cluster, and to have your controllers tucked away neatly, and with the functions passed in lieu of the anonymous ones. Hopefully, these will get you started.

var authenticate = function (client, username, password, callback) {
 console.log('ping ', username);
    // if (username == "test" && password.toString() == "test")
        callback(null, true);
    // else
    //     callback(null, false);
}

var authorizePublish = function (client, topic, payload, callback) {
    callback(null, true);
}

var authorizeSubscribe = function (client, topic, callback) {
    callback(null, true);
}

var mosca = require('mosca');

var ascoltatore = {
 type: 'mongo',
 url: 'mongodb://localhost:27017/mqtt',
 pubsubCollection: 'ascoltatori',
 mongo: {}
};

var moscaSetting = {
 port: 1883,
 host: "192.168.foo.bar", // specify an host to bind to a single interface
 logger: {
  level: 'debug'
 },
 persistence: {
     factory: mosca.persistence.Mongo,
     url: 'mongodb://localhost:27017/mqtt'
   },
 backend: ascoltatore
};

var http     = require('http')
  , dispatch = require('dispatch')
  , broker = new mosca.Server(moscaSetting);

httpServ = http.createServer(
 dispatch({
        '/': function(req, res, next){
            console.log('alpha romeo');
        },
        '/user/:id': function(req, res, next, id){
            // ...
        },
        '/user/posts': function(req, res, next){
            // ...
        },
        '/user/posts/(\\w+)': function(req, res, next, post){
            // ...
        }
    })
);

broker.attachHttpServer(httpServ);

httpServ.listen(3000);

broker.on('ready', setup);

function setup() {
    broker.authenticate = authenticate;
    broker.authorizePublish = authorizePublish;
    broker.authorizeSubscribe = authorizeSubscribe;
    
    console.log('Mosca broker is up and running.');
}

broker.on("error", function (err) {
    console.log(err);
});

broker.on('clientConnected', function (client) {
    console.log('Client Connected \t:= ', client.id);
});

broker.on('published', function (packet, client) {
    console.log("Published :=", packet);
});

broker.on('subscribed', function (topic, client) {
    console.log("Subscribed :=", client.packet);
});

broker.on('unsubscribed', function (topic, client) {
    console.log('unsubscribed := ', topic);
});

broker.on('clientDisconnecting', function (client) {
    console.log('clientDisconnecting := ', client.id);
});

broker.on('clientDisconnected', function (client) {
    console.log('Client Disconnected     := ', client.id);
});

Check out the full project on Github

31 January 2015

Optional Javascript Function Parameters

Optional parameters can be included in Javascript functions without the need to specify a default value. Some view this as a bug in Javascript that can miss errors, while others view it as a flexibility similar to what can be observed in life.

>>> def xyz (a, b, c=None):
...   print (a)
...   print (b)
...   if (c):
...     print (c)
... 
>>> xyz(1,2,3)
1
2
3
>>> xyz(1,2)
1
2


Without specifying a default 'None' value, the function would throw an exception if there is arity mismatch, as would be in C, ML, and just about every other strong or static procedural or functional language. In Javascript, however, the parameter's use is only bound to their reliance within the function. It would be

> function xyz (a, b, c) {
... console.log(a)
... console.log(b)
... if (c) { console.log(c) }
... }
> xyz(1,2,3)
1
2
3
> xyz(1,2)
1
2

27 November 2014

Core-Template Tutorial

To get started, we need a static html server with the web components available for import.

The main display will be the index.html file, and templates will be placed in the templates directory:

|-myproj
  |-server
  |-public
     |-views
  |-components
  |-templates


We'll create a basic element to display how to use this feature.

Within a bare index.html file, we'll try to create a basic core element object:

<polymer-element>
  <template>
    <p>Hello World!</p>
  </template>
</polymer-element>


The index.html file with the basic core element will look like:

<!doctype html>
<html>
  <head>
    <script src="../components/webcomponentsjs/webcomponents.js"></script>
    <link rel="import" href="../components/polymer/polymer.html">
  </head>
  <body unresolved>
    <polymer-element>
      <template>
        <p>Hello World!</p>
      </template>
    </polymer-element>
  </body>
</html>


You'll run this file on your browser via your server, and notice that nothing is displayed on the screen. How come? It seems that using literal web-components is disallowed, and, in any case to create elements this way would create an unmanageable project in a hurry.

The solution is to modularize your components, and reference them by their name property wherever in the index.html they will be used.

The basic core element we created will be moved to a templates/hello_world.html file, along with it's dependency:

(templates/hello_world.html)

<link rel="import" href="../components/polymer/polymer.html">

<polymer-element name="hello-world" noscript>
  <template>
    <p>Hello World!</p>
  </template>
</polymer-element>


We'll import the hello_world.html file in the index.html, and create an instance of the component within the body tag:

<!doctype html>
<html>
  <head>
    <script src="../components/webcomponentsjs/webcomponents.js"></script>
    <link rel="import" href="../templates/hello_world.html">
  </head>
  <body unresolved>
    <hello-world></hello-world>
  </body>
</html>


When the index.html is accessed from the server to the browser, you'll see your template displayed. Even the very basic example we have includes a slick fade effect, and the affect of web-components could not be highlighted more elegantly.

We'll continue by adding a button to the template:

(templates/hello_world.html)

<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="../components/paper-button/paper-button.html">

<polymer-element name="hello-world" noscript>
  <template>
    <p>Hello World!</p>
    <paper-button><span>Yo</span></paper-button>
  </template>
</polymer-element>


The button is added to the view, and we can configure a view element using the core-card element to contain our content:

(templates/hello_world.html)

<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="../components/paper-button/paper-button.html">

<polymer-element name="hello-world" noscript>
  <template>
  <div style="background-color:pink; float:left;">
   <p>Hello World!</p>
   <paper-button on-click="{{hello}}" raised><span>Yo</span></paper-button>
</div>
  </template>
  <script>
  Polymer({
      hello: function() {
        console.log('yo, hello!');
      }
    });
  </script>
</polymer-element>


Try to run the code, and you'll notice a console error stating "Uncaught Already registered (Polymer) prototype for element hello-world". That's because the 'noscript' option has already locked the Polymer script, and if you remove that option, and run the code again there will be no error. By clicking the button, you will see the corresponding results of the hello function displayed.

23 November 2014

How to get up and running with Node.js and Polymer

So, the first thing, really, coming from a Node.js perspective, that is previous experience with Javascript and little or none with Polymer, is to understand, really, what is Polymer.

According to the awesome Google Evangelists, it's clear that Polymer is a refactor of the browser API, wherein HTML5 and CSS capabilities are optimized to make life on the front-end more tolerable, and to provide end-users with a more coherent user experience. Think of it as UIKit, for you iOS'ers, on the browser. With that, Polymer may be in a similar competing space as others, such as famo.us.

However, Polymer is unique in that it is an HTML-side only technology. The binding comes native with the browser. So where others leave it to the developer to implement their bindings on the server, with Polymer, the server is simply interacting with the browser. Hence, the browser handles the binding, and the entirety of the UI with the use of Web Components and Shadow DOM (DOM within the DOM). For now, you'll have to install components in to your app, but don't be surprised that in the future there will no longer be a need to install core components in an app, custom components will likely remain imported.

A more thorough discussion of what is Polymer can be found at http://www.toptal.com/front-end/polymer-js-the-future-of-web-application-development

After reading through, and spending time to find how or what is this technology, and how to use it-- it became more clear that it is simply a more direct way to utilize HTML, and make more simple design, hence more solid, applications. I'm going to walk through some of the steps I took to get started with Polymer on Node.js.

The cleanest implementation of a static HTML file server exists in the express framework:

var express = require('express') // express 4
  , app = express() 
  , port = 1117
  , ipaddr = 'localhost';


app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});


app.listen(port, ipaddr, function() {
  console.log("Server up on " + ipaddr + ":" + port);
});


The next step was to import the components. I opted for the lazy way, and drag and dropped them from the zip file that was provided by the tutorial.

The structure of the app became like so following the integration of components:

toplevel dir ------------
                     |
                   server.js
public -----------
                                  |
                            index.html
  node_modules -
                                  |
                              express
  components ----
                                  |
                             web components here

I also used the Polymer HTML sample code (https://www.polymer-project.org/docs/start/tutorial/intro.html). The index.html file was:

<!doctype html><html><head>  <title>unquote</title>  <meta name="viewport"  content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">  <script src="../components/webcomponentsjs/webcomponents.js">  </script>  <link rel="import" href="../components/font-roboto/roboto.html">  <link rel="import"    href="../components/core-header-panel/core-header-panel.html">  <link rel="import"    href="../components/core-toolbar/core-toolbar.html">  <link rel="import"    href="../components/paper-tabs/paper-tabs.html">  <style>  html,body {    height: 100%;    margin: 0;    background-color: #E5E5E5;    font-family: 'RobotoDraft', sans-serif;  }  core-header-panel {    height: 100%;    overflow: auto;    -webkit-overflow-scrolling: touch;  }  core-toolbar {    background: #03a9f4;    color: white;  }  #tabs {    width: 100%;    margin: 0;    -webkit-user-select: none;    -moz-user-select: none;    -ms-user-select: none;    user-select: none;    text-transform: uppercase;  }  .container {    width: 80%;    margin: 50px auto;  }  @media (min-width: 481px) {    #tabs {      width: 200px;    }    .container {      width: 400px;    }  }  </style></head><body unresolved>  <core-header-panel>    <core-toolbar>      <paper-tabs id="tabs" selected="all" self-end>        <paper-tab name="all">All</paper-tab>        <paper-tab name="favorites">Favorites</paper-tab>      </paper-tabs>    </core-toolbar>    <!-- main page content will go here -->  </core-header-panel>  <script>    var tabs = document.querySelector('paper-tabs');    tabs.addEventListener('core-select', function(e) {      console.log("Selected: " + tabs.selected);    });  </script></body></html>



To have the components path accessible for the static resources, server.js was modified to include:

app.use("/components", express.static(__dirname + '/components'));


By starting the app and visiting the port on the browser, it became clear that the magic of Polymer was indeed in action. The few lines displayed a very zen-like user interface, and excitement began to ensue.

In essence, you can get a Polymer app going with the following server.js file:

// configure API
var express = require('express') // express 4
  , environment = require('./env.js')
  , app = express() 
  , port = environment.PORT
  , ipaddr = environment.IPDR;

app.use("/components", express.static(__dirname + '/components'));

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});


app.listen(port, ipaddr, function() {
  console.log("Server up on " + ipaddr + ":" + port);
});


Add the HTML, and run the following dependencies.sh file to add your project dependencies:

#!/bin/bash

# install express 4
npm install --save express@4.x.x

# add Polymer to project
mkdir polymer_local; cd polymer_local
git clone https://github.com/Polymer/tools.git
./tools/bin/pull-all.sh

# move components dir
mv components ../components

# cleanup
cd ..
rm -rf polymer_local


It takes a while for the script to load (~350MB of downloads!!). At that point you will have many web components available, and including some pretty cool instruments that I know will keep me busy from some time to come.

Here are a couple of the many resources available for your practice:

https://www.polymer-project.org/docs/start/creatingelements.html
http://code.tutsplus.com/tutorials/using-polymer-to-create-web-components--cms-20475
http://customelements.io/
http://ebidel.github.io/material-playground/
https://www.polymer-project.org/tools/designer/
http://www.ibm.com/developerworks/library/wa-polymer/

I hope this helps you to rock and roll with Node.js and Polymer. Enjoy.

07 August 2014

Delegate pattern with Backbone.js

Backbone.js comes with a built-in Event handler, known as Backbone.Events whose implementation is described well in the LosTechies article found here.

However, the pattern is really known as Aggregation pattern; and a method in one view controller can be invoked within another view controller.

The reason it is not readily a delegate pattern deals with the issue of scope respective to Javascript. The view controller who invoked the method of another view controller does so within their own scope, and local variables are then not recognized:

// viewcontroller 1
vent.trigger('foo')

// viewcontroller2
foo: function() {
  console.log('this.foobar', this.foobar)
}

// console
this.foobar unknown


In order to make the view controller able to reference values local to itself, a small modification can be made to the traditional `bind` of the Backbone.Events variable:

this.vent = Backbone.Events('foo', function() {
  this.foo();
});

Here, the anonymous function references the function within the scope of the original view controller. Now when the same code is run, the output will be the value of `this.foobar`. Run delegate pattern with Backbone.js using Backbone.Events!